@clawos-dev/clawd 0.2.686 → 0.2.688

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -43380,7 +43380,7 @@ var require_websocket = __commonJS({
43380
43380
  var http2 = require("http");
43381
43381
  var net2 = require("net");
43382
43382
  var tls = require("tls");
43383
- var { randomBytes: randomBytes2, createHash: createHash5 } = require("crypto");
43383
+ var { randomBytes: randomBytes2, createHash: createHash6 } = require("crypto");
43384
43384
  var { Duplex, Readable: Readable4 } = require("stream");
43385
43385
  var { URL: URL2 } = require("url");
43386
43386
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -44040,7 +44040,7 @@ var require_websocket = __commonJS({
44040
44040
  abortHandshake(websocket, socket, "Invalid Upgrade header");
44041
44041
  return;
44042
44042
  }
44043
- const digest = createHash5("sha1").update(key + GUID).digest("base64");
44043
+ const digest = createHash6("sha1").update(key + GUID).digest("base64");
44044
44044
  if (res.headers["sec-websocket-accept"] !== digest) {
44045
44045
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
44046
44046
  return;
@@ -44407,7 +44407,7 @@ var require_websocket_server = __commonJS({
44407
44407
  var EventEmitter2 = require("events");
44408
44408
  var http2 = require("http");
44409
44409
  var { Duplex } = require("stream");
44410
- var { createHash: createHash5 } = require("crypto");
44410
+ var { createHash: createHash6 } = require("crypto");
44411
44411
  var extension2 = require_extension();
44412
44412
  var PerMessageDeflate2 = require_permessage_deflate();
44413
44413
  var subprotocol2 = require_subprotocol();
@@ -44708,7 +44708,7 @@ var require_websocket_server = __commonJS({
44708
44708
  );
44709
44709
  }
44710
44710
  if (this._state > RUNNING) return abortHandshake(socket, 503);
44711
- const digest = createHash5("sha1").update(key + GUID).digest("base64");
44711
+ const digest = createHash6("sha1").update(key + GUID).digest("base64");
44712
44712
  const headers = [
44713
44713
  "HTTP/1.1 101 Switching Protocols",
44714
44714
  "Upgrade: websocket",
@@ -53581,6 +53581,10 @@ async function centralRequest(opts, path111, init) {
53581
53581
  }
53582
53582
  clearTimeout(timer);
53583
53583
  if (res.status === 401) {
53584
+ const detail = await res.json().catch(() => null);
53585
+ if (path111 === "/api/persona-cloud/github/oauth/token" && detail?.errorCode === "GITHUB_REAUTH_REQUIRED") {
53586
+ throw new CentralClientError("API_ERROR", typeof detail.message === "string" ? detail.message : "\u8BF7\u91CD\u65B0\u5173\u8054 GitHub", void 0, 401);
53587
+ }
53584
53588
  throw new CentralClientError("UNAUTHORIZED", "login pass rejected by center");
53585
53589
  }
53586
53590
  if (!res.ok) {
@@ -53759,11 +53763,12 @@ async function centralGithubAuthToken(opts) {
53759
53763
  const body = await centralRequest(opts, "/api/persona-cloud/github/oauth/token", {
53760
53764
  method: "POST",
53761
53765
  bearer: opts.loginPass,
53762
- body: {}
53766
+ body: { ...opts.rejectedToken ? { rejectedToken: opts.rejectedToken } : {} }
53763
53767
  });
53764
53768
  if (body.token === null || body.token === void 0) return void 0;
53765
53769
  if (typeof body.token !== "string" || !body.token) throw new CentralClientError("BAD_RESPONSE", "github/oauth/token: malformed token");
53766
- return { token: body.token, login: typeof body.login === "string" ? body.login : "" };
53770
+ if (body.expiresAt !== void 0 && (typeof body.expiresAt !== "string" || !Number.isFinite(Date.parse(body.expiresAt)))) throw new CentralClientError("BAD_RESPONSE", "github/oauth/token: malformed expiry");
53771
+ return { token: body.token, login: typeof body.login === "string" ? body.login : "", ...typeof body.expiresAt === "string" ? { expiresAt: body.expiresAt } : {} };
53767
53772
  }
53768
53773
  async function centralClaimPublisher(opts) {
53769
53774
  await centralRequest(opts, `/api/persona-cloud/personas/${encodeURIComponent(opts.personaId)}/publisher`, {
@@ -57519,8 +57524,8 @@ function createGhRunner(defaults) {
57519
57524
  const baseTimeoutMs = defaults?.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
57520
57525
  const spawn17 = defaults?.execFile ?? import_node_child_process9.execFile;
57521
57526
  return {
57522
- run(args, opts) {
57523
- const token = defaults?.token?.();
57527
+ async run(args, opts) {
57528
+ const token = await defaults?.token?.();
57524
57529
  return new Promise((resolve9, reject) => {
57525
57530
  spawn17(
57526
57531
  "gh",
@@ -62165,23 +62170,38 @@ function createGithubApi(args) {
62165
62170
  const seal = args.seal ?? sealWithSodium;
62166
62171
  const timeoutMs = args.timeoutMs ?? TIMEOUT_MS;
62167
62172
  const secretsPath = (slug, environment) => `/repos/${slug}/${environment ? `environments/${encodeURIComponent(environment)}` : "actions"}/secrets`;
62168
- async function request(method, path111, body) {
62169
- let res;
62170
- try {
62171
- res = await doFetch(`${API}${path111}`, {
62172
- method,
62173
- headers: {
62174
- Authorization: `Bearer ${args.token}`,
62175
- Accept: "application/vnd.github+json",
62176
- "X-GitHub-Api-Version": "2022-11-28",
62177
- ...body !== void 0 ? { "Content-Type": "application/json" } : {}
62178
- },
62179
- ...body !== void 0 ? { body: JSON.stringify(body) } : {},
62180
- signal: AbortSignal.timeout(timeoutMs)
62181
- });
62182
- } catch (err) {
62183
- throw new GithubApiError(0, `\u8FDE\u4E0D\u4E0A GitHub\uFF1A${err instanceof Error ? err.message : String(err)}`);
62173
+ async function authenticatedFetch(path111, init) {
62174
+ let token = args.identity ? (await args.identity.refresh())?.token : args.token;
62175
+ if (!token) throw new GithubApiError(401, "\u8BF7\u5148\u5173\u8054 GitHub");
62176
+ for (let attempt = 0; ; attempt++) {
62177
+ let res;
62178
+ try {
62179
+ res = await doFetch(API + path111, {
62180
+ ...init,
62181
+ headers: { ...init.headers, Authorization: "Bearer " + token },
62182
+ signal: AbortSignal.timeout(timeoutMs)
62183
+ });
62184
+ } catch (err) {
62185
+ throw new GithubApiError(0, "\u8FDE\u4E0D\u4E0A GitHub\uFF1A" + (err instanceof Error ? err.message : String(err)));
62186
+ }
62187
+ if (res.status !== 401 || attempt !== 0 || !args.identity) return res;
62188
+ const renewed = await args.identity.recover(token);
62189
+ if (!renewed || renewed.token === token) return res;
62190
+ await res.body?.cancel();
62191
+ token = renewed.token;
62184
62192
  }
62193
+ }
62194
+ async function request(method, path111, body) {
62195
+ const res = await authenticatedFetch(path111, {
62196
+ method,
62197
+ redirect: "error",
62198
+ headers: {
62199
+ Accept: "application/vnd.github+json",
62200
+ "X-GitHub-Api-Version": "2022-11-28",
62201
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
62202
+ },
62203
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
62204
+ });
62185
62205
  const text = await res.text();
62186
62206
  let json = void 0;
62187
62207
  if (text) {
@@ -62266,8 +62286,8 @@ function createGithubApi(args) {
62266
62286
  const signal = AbortSignal.timeout(timeoutMs);
62267
62287
  let res;
62268
62288
  try {
62269
- res = await doFetch(`${API}/repos/${slug}/actions/artifacts/${artifactId}/zip`, {
62270
- headers: { Authorization: `Bearer ${args.token}`, Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" },
62289
+ res = await authenticatedFetch(`/repos/${slug}/actions/artifacts/${artifactId}/zip`, {
62290
+ headers: { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" },
62271
62291
  redirect: "manual",
62272
62292
  signal
62273
62293
  });
@@ -62892,7 +62912,8 @@ function networkOptions(auth) {
62892
62912
  return auth?.source === "file" ? { prefix: [...QUIET_GIT_ARGS, "-c", "credential.helper=", "-c", `credential.helper=${INLINE_HELPER}`], env: { ...QUIET_GIT_ENV, CLAWD_GITHUB_TOKEN: auth.token } } : { prefix: [...QUIET_GIT_ARGS], env: QUIET_GIT_ENV };
62893
62913
  }
62894
62914
  async function networkGit(exec, dir, auth, args, what) {
62895
- const opts = networkOptions(auth);
62915
+ const current = typeof auth === "function" ? await auth() : auth;
62916
+ const opts = networkOptions(current);
62896
62917
  return mustGit(exec, dir, [...opts.prefix, ...args], what, { timeoutMs: 12e4, env: opts.env });
62897
62918
  }
62898
62919
  async function gitPush(exec, dir, auth, refspec = "HEAD:refs/heads/integration") {
@@ -63807,7 +63828,11 @@ function buildDeployHandlers(deps) {
63807
63828
  async function requireGithub() {
63808
63829
  const auth = await deps.githubIdentity.refresh();
63809
63830
  if (!auth) throw new ClawdError(ERROR_CODES.INTERNAL, NO_GITHUB_AUTH);
63810
- return { auth, api: deps.githubApi(auth.token) };
63831
+ return { auth: async () => {
63832
+ const current = await deps.githubIdentity.refresh();
63833
+ if (!current) throw new ClawdError(ERROR_CODES.INTERNAL, NO_GITHUB_AUTH);
63834
+ return current;
63835
+ }, api: deps.githubApi(auth.token) };
63811
63836
  }
63812
63837
  function mustPersona(personaId2) {
63813
63838
  if (!deps.hasPersona(personaId2)) {
@@ -65032,13 +65057,82 @@ function createGithubIdentity(deps) {
65032
65057
  let pendingOauth = null;
65033
65058
  let staleCenterToken;
65034
65059
  const listeners = /* @__PURE__ */ new Set();
65035
- async function refresh() {
65036
- const mine = ++seq;
65037
- const resolved = await deps.resolve();
65038
- if (mine === seq) auth = resolved;
65039
- return resolved;
65060
+ let managedToken;
65061
+ const oauthCandidate = (token) => /^gh[ou]_/.test(token);
65062
+ const oauthManaged = (token) => oauthCandidate(token) && (managedToken === token || deps.isManaged?.(token) === true);
65063
+ let acquisition;
65064
+ let centerFlight;
65065
+ let centerCache;
65066
+ let writes = Promise.resolve();
65067
+ function remember(got) {
65068
+ const expiry = got.expiresAt ? Date.parse(got.expiresAt) - 6e4 : Infinity;
65069
+ centerCache = { token: got.token, until: Math.min(deps.now() + 2e4, expiry) };
65070
+ }
65071
+ function persist(token, generation, managed = false) {
65072
+ const write = writes.catch(() => {
65073
+ }).then(async () => {
65074
+ if (generation !== seq) return;
65075
+ const stored = await deps.store(token);
65076
+ if (generation !== seq) return;
65077
+ deps.markManaged?.(managed ? token : void 0);
65078
+ managedToken = managed ? token : void 0;
65079
+ auth = stored;
65080
+ statusCache.clear();
65081
+ pendingOauth = null;
65082
+ for (const cb of listeners) cb();
65083
+ });
65084
+ writes = write;
65085
+ return write;
65086
+ }
65087
+ async function syncCenter(local, rejectedToken) {
65088
+ if (!oauthCandidate(local.token)) return local;
65089
+ const managed = oauthManaged(local.token);
65090
+ if (!rejectedToken && centerCache?.token === local.token && deps.now() < centerCache.until) return local;
65091
+ if (centerFlight) return centerFlight;
65092
+ const generation = seq;
65093
+ const task = (async () => {
65094
+ let got;
65095
+ try {
65096
+ got = await deps.oauth.token(rejectedToken);
65097
+ } catch (err) {
65098
+ if (managed) throw err;
65099
+ return local;
65100
+ }
65101
+ if (generation !== seq) return auth;
65102
+ if (!got || !managed && got.token !== local.token) {
65103
+ remember({ token: local.token });
65104
+ return local;
65105
+ }
65106
+ if (!managed || got.token !== local.token) await persist(got.token, generation, true);
65107
+ if (generation !== seq) return auth;
65108
+ remember(got);
65109
+ return auth ?? local;
65110
+ })().finally(() => {
65111
+ if (centerFlight === task) centerFlight = void 0;
65112
+ });
65113
+ centerFlight = task;
65114
+ return task;
65115
+ }
65116
+ function refresh() {
65117
+ if (acquisition) return acquisition;
65118
+ const generation = seq;
65119
+ const task = (async () => {
65120
+ const resolved = await deps.resolve();
65121
+ if (generation !== seq) return auth;
65122
+ auth = resolved;
65123
+ return resolved ? syncCenter(resolved) : void 0;
65124
+ })().finally(() => {
65125
+ if (acquisition === task) acquisition = void 0;
65126
+ });
65127
+ acquisition = task;
65128
+ return task;
65129
+ }
65130
+ async function recover(rejectedToken) {
65131
+ const current = await refresh();
65132
+ if (!current || current.token !== rejectedToken || !oauthManaged(current.token)) return current;
65133
+ return syncCenter(current, rejectedToken);
65040
65134
  }
65041
- async function whoami(a2) {
65135
+ async function whoami(a2, recovering = false) {
65042
65136
  const hit = statusCache.get(a2.token);
65043
65137
  if (hit && deps.now() - hit.at < cacheMs) return hit.status;
65044
65138
  let status2;
@@ -65046,19 +65140,26 @@ function createGithubIdentity(deps) {
65046
65140
  const { login } = await deps.api(a2.token).whoami();
65047
65141
  status2 = { status: "authorized", login, source: a2.source };
65048
65142
  } catch (err) {
65143
+ if (!recovering && err instanceof GithubApiError && err.status === 401 && oauthManaged(a2.token)) {
65144
+ try {
65145
+ const renewed = await recover(a2.token);
65146
+ if (renewed && renewed.token !== a2.token) return whoami(renewed, true);
65147
+ } catch (recoveryError) {
65148
+ return { status: "invalid", message: recoveryError instanceof Error ? recoveryError.message : String(recoveryError) };
65149
+ }
65150
+ }
65049
65151
  status2 = { status: "invalid", message: err instanceof Error ? err.message : String(err) };
65050
65152
  }
65051
65153
  statusCache.set(a2.token, { at: deps.now(), status: status2 });
65052
65154
  return status2;
65053
65155
  }
65054
65156
  async function adopt(token) {
65055
- auth = await deps.store(token);
65056
- seq++;
65057
- statusCache.clear();
65058
- pendingOauth = null;
65059
- for (const cb of listeners) cb();
65157
+ const generation = ++seq;
65158
+ centerCache = void 0;
65159
+ await persist(token, generation);
65060
65160
  }
65061
65161
  async function claimCenterToken() {
65162
+ const generation = seq;
65062
65163
  let got;
65063
65164
  try {
65064
65165
  got = await deps.oauth.token();
@@ -65072,7 +65173,9 @@ function createGithubIdentity(deps) {
65072
65173
  if (err instanceof GithubApiError && err.status === 401) staleCenterToken = got.token;
65073
65174
  return false;
65074
65175
  }
65075
- await adopt(got.token);
65176
+ if (generation !== seq) return false;
65177
+ await persist(got.token, ++seq, true);
65178
+ remember(got);
65076
65179
  return true;
65077
65180
  }
65078
65181
  async function settlePendingOauth() {
@@ -65090,13 +65193,19 @@ function createGithubIdentity(deps) {
65090
65193
  }
65091
65194
  async function status() {
65092
65195
  await settlePendingOauth();
65093
- const a2 = await refresh();
65196
+ let a2;
65197
+ try {
65198
+ a2 = await refresh();
65199
+ } catch (err) {
65200
+ return { status: "invalid", message: err instanceof Error ? err.message : String(err) };
65201
+ }
65094
65202
  const current = a2 ? await whoami(a2) : { status: "missing" };
65095
65203
  return pendingOauth && current.status !== "authorized" ? { status: "pending", authUrl: pendingOauth.authUrl } : current;
65096
65204
  }
65097
65205
  return {
65098
65206
  cached: () => auth,
65099
65207
  refresh,
65208
+ recover,
65100
65209
  status,
65101
65210
  adopt,
65102
65211
  async authorize(raw) {
@@ -65111,7 +65220,7 @@ function createGithubIdentity(deps) {
65111
65220
  },
65112
65221
  // 已有身份时重新授权;直接返回 pending 链接,不能经 status() 被旧的 authorized 状态遮掉。
65113
65222
  async oauthStart(returnTo) {
65114
- const local = await refresh();
65223
+ const local = await deps.resolve();
65115
65224
  if (!local && await claimCenterToken()) return status();
65116
65225
  try {
65117
65226
  staleCenterToken = (await deps.oauth.token())?.token;
@@ -75363,7 +75472,7 @@ function computeMethodAccess(args) {
75363
75472
  }
75364
75473
 
75365
75474
  // src/version.ts
75366
- var version = "0.2.686".length > 0 ? "0.2.686" : "dev";
75475
+ var version = "0.2.688".length > 0 ? "0.2.688" : "dev";
75367
75476
 
75368
75477
  // src/cli-probe/probe.ts
75369
75478
  var fs86 = __toESM(require("fs"), 1);
@@ -78051,7 +78160,14 @@ async function startDaemon(config) {
78051
78160
  const localSecretsDir = import_node_path89.default.join(config.dataDir, LOCAL_SECRETS_DIRNAME);
78052
78161
  const readSecrets = () => readSecretTable({ bundleRoot: secretsBundleRoot, overrideDir: localSecretsDir, logger });
78053
78162
  const githubTokenFile = import_node_path89.default.join(localSecretsDir, GITHUB_TOKEN_FILE);
78163
+ const managedGithubVar = "CLAWD_GITHUB_MANAGED_TOKEN_SHA256";
78164
+ const githubFingerprint = (token) => (0, import_node_crypto30.createHash)("sha256").update(token).digest("hex");
78054
78165
  const githubIdentity = createGithubIdentity({
78166
+ isManaged: (token) => readEnvFileVar(githubTokenFile, managedGithubVar) === githubFingerprint(token),
78167
+ markManaged: (token) => {
78168
+ if (token) upsertEnvFileVar(githubTokenFile, managedGithubVar, githubFingerprint(token));
78169
+ else removeEnvFileVar(githubTokenFile, managedGithubVar);
78170
+ },
78055
78171
  resolve: () => resolveGithubAuth({ exec: runCommand, fileToken: () => readEnvFileVar(githubTokenFile, GITHUB_TOKEN_VAR) }),
78056
78172
  store: (token) => storeGithubAuth({
78057
78173
  exec: runCommand,
@@ -78073,19 +78189,23 @@ async function startDaemon(config) {
78073
78189
  throw new ClawdError(ERROR_CODES.INTERNAL, `\u5411\u4E2D\u5FC3\u8981 GitHub \u6388\u6743\u94FE\u63A5\u6CA1\u6210\uFF1A${err instanceof Error ? err.message : String(err)}`);
78074
78190
  }
78075
78191
  },
78076
- token: async () => {
78192
+ token: async (rejectedToken) => {
78077
78193
  const r2 = ownerIdentityStore.read();
78078
78194
  if (!r2) return void 0;
78079
- return centralGithubAuthToken({ api: config.clawosApi ?? DEFAULT_CLAWOS_API, loginPass: r2.loginPass });
78195
+ return centralGithubAuthToken({ api: config.clawosApi ?? DEFAULT_CLAWOS_API, loginPass: r2.loginPass, ...rejectedToken ? { rejectedToken } : {} });
78080
78196
  }
78081
78197
  },
78082
78198
  now: () => Date.now(),
78083
78199
  logger
78084
78200
  });
78085
- void githubIdentity.refresh();
78201
+ void githubIdentity.refresh().catch(() => {
78202
+ logger.warn("github.identity.warm-failed");
78203
+ });
78086
78204
  const resolvePersonaMcpConfig = (personaId2) => {
78087
78205
  const secrets = secretsWithGithubIdentity(readSecrets(), githubIdentity.cached());
78088
- void githubIdentity.refresh();
78206
+ void githubIdentity.refresh().catch(() => {
78207
+ logger.warn("github.identity.sync-failed");
78208
+ });
78089
78209
  return renderPersonaMcpSecrets({
78090
78210
  personaId: personaId2,
78091
78211
  personaDir: import_node_path89.default.join(config.dataDir, "personas", personaId2),
@@ -78913,7 +79033,7 @@ async function startDaemon(config) {
78913
79033
  shiftStore,
78914
79034
  shiftOwnerIdProvider: () => ownerPrincipalId,
78915
79035
  // PR 收件箱:github:* handler spawn 本机 gh CLI,凭据是 clawd 的 GitHub 身份(GH_TOKEN),没有才是 gh 自己的登录态
78916
- ghRunner: createGhRunner({ token: () => githubIdentity.cached()?.token }),
79036
+ ghRunner: createGhRunner({ token: async () => (await githubIdentity.refresh())?.token }),
78917
79037
  githubIdentity,
78918
79038
  visitorStore
78919
79039
  })
@@ -79023,7 +79143,7 @@ async function startDaemon(config) {
79023
79143
  fetchArtifact: downloadArtifact(runCommand),
79024
79144
  debianPackage: lookupDebianPackage(),
79025
79145
  githubIdentity,
79026
- githubApi: (token) => createGithubApi({ token }),
79146
+ githubApi: (token) => createGithubApi({ token, identity: githubIdentity }),
79027
79147
  org: PERSONA_REPO_ORG,
79028
79148
  claimPublisher: async (personaId2, environment = "production") => {
79029
79149
  const loginPass = targetLoginPass(environment);
@@ -619,5 +619,5 @@ Minimum version required to store current data is: `+s+`.
619
619
 
620
620
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
621
621
 
622
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return g.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Bce="DialogDescriptionWarning",$ce=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${YA(Bce).contentName}}.`;return g.useEffect(()=>{var s;const i=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&i&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},zce=DA,Fce=$A,XA=zA,ZA=FA,QA=UA,JA=qA,Hce=KA;const ej=zce,Uce=Fce,tj=g.forwardRef(({className:e,...t},n)=>h.jsx(XA,{ref:n,className:re("fixed inset-0 z-50 bg-black/50 backdrop-blur-sm",e),...t}));tj.displayName=XA.displayName;const Eb=g.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(Uce,{children:[h.jsx(tj,{}),h.jsxs(ZA,{ref:r,className:re("fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2","gap-4 rounded-lg border border-border bg-elevated p-6 shadow-lg",e),...n,children:[t,h.jsxs(Hce,{className:"absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-accent",children:[h.jsx(Qr,{className:"h-4 w-4"}),h.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Eb.displayName=ZA.displayName;const nj=({className:e,...t})=>h.jsx("div",{className:re("flex flex-col space-y-1.5 text-left",e),...t});nj.displayName="DialogHeader";const Ib=g.forwardRef(({className:e,...t},n)=>h.jsx(QA,{ref:n,className:re("text-lg font-semibold leading-none text-text-100",e),...t}));Ib.displayName=QA.displayName;const rj=g.forwardRef(({className:e,...t},n)=>h.jsx(JA,{ref:n,className:re("text-sm text-text-300",e),...t}));rj.displayName=JA.displayName;function Wce({persona:e,open:t,onClose:n,onDelete:r,embedded:i,onLoadPersonality:s,onSavePersonality:o,onLoadPersonalityLocal:a,onSavePersonalityLocal:l,hasPersonalityLocal:c=!1,onDirtyChange:u,initialPersonality:d,onShareCapability:f,readOnly:p=!1,larkBot:m}){const[x,w]=g.useState(!1),[v,_]=g.useState(!1),b=x||v,S=Qe.useRef(u);g.useEffect(()=>{S.current=u}),g.useEffect(()=>{var k;(k=S.current)==null||k.call(S,b)},[b]);const C=()=>{b&&!window.confirm("修改未保存,确定关闭?")||n()};return t?h.jsxs(h.Fragment,{children:[!i&&h.jsx("div",{className:"absolute inset-0 z-30 bg-black/30",onClick:C,"aria-hidden":"true"}),h.jsxs("aside",{className:i?"flex h-full w-full flex-col bg-bg-0":"absolute right-0 top-0 z-40 flex h-full w-[420px] flex-col bg-bg-0 border-l border-border shadow-xl","data-testid":"persona-settings-drawer",children:[h.jsxs("header",{className:"flex items-center justify-between border-b border-border px-4 py-3 shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[h.jsx(IF,{className:"h-4 w-4 text-text-300"}),h.jsx("span",{className:"text-[13px] font-medium text-text-100 truncate",children:"Persona 设置"})]}),h.jsx("button",{type:"button",onClick:C,"aria-label":"关闭",className:"rounded-sm p-1.5 text-text-400 hover:bg-bg-200 hover:text-text-100",children:h.jsx(Qr,{className:"h-4 w-4"})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto p-6 flex flex-col gap-4",children:[h.jsxs("header",{className:"flex items-start justify-between gap-3",children:[h.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("h2",{className:"text-lg font-semibold text-text-100 truncate",children:e.label}),e.public?h.jsxs("span",{className:"inline-flex items-center gap-1 rounded-sm bg-bg-200 px-1.5 py-0.5 text-[10px] text-text-200",children:[h.jsx(V7,{className:"h-3 w-3"})," 公开"]}):h.jsxs("span",{className:"inline-flex items-center gap-1 rounded-sm bg-error-dim px-1.5 py-0.5 text-[10px] text-error",children:[h.jsx(W7,{className:"h-3 w-3"})," 已关闭"]})]}),h.jsx("span",{className:"font-mono text-[11px] text-text-400 truncate","data-testid":"persona-id-subtitle",children:e.personaId})]}),h.jsxs("div",{className:"flex items-center gap-1",children:[f?h.jsxs("button",{type:"button",onClick:f,"aria-label":"分享给他人",title:"分享给他人",className:"inline-flex items-center gap-1 rounded-sm px-2 py-1.5 text-xs text-text-200 hover:bg-bg-200 hover:text-text-100",children:[h.jsx(Qy,{className:"h-3.5 w-3.5"}),"分享"]}):null,r?h.jsx("button",{type:"button",onClick:r,"aria-label":"删除 persona",className:"rounded-sm p-1.5 text-text-400 hover:bg-bg-200 hover:text-error",children:h.jsx(Jy,{className:"h-4 w-4"})}):null]})]}),h.jsx("hr",{className:"border-border"}),m?h.jsxs(h.Fragment,{children:[h.jsx(Kce,{...m}),h.jsx("hr",{className:"border-border"})]}):null,s?h.jsxs(h.Fragment,{children:[h.jsx(CE,{onLoad:s,...o&&!e.personalityManaged?{onSave:o}:{},onDirtyChange:w,initialPersonality:d,readOnly:p||!!e.personalityManaged,title:e.personalityManaged?"内置人格":"人格 (Personality)",hint:e.personalityManaged?p?"这个 persona 自带的人格,随 clawd 版本更新。":"这个 persona 自带的人格,随 clawd 版本更新——在这里改不会保留,要加自己的规则请写下面的「你的补充」。":void 0,testIdPrefix:"persona-personality"}),(e.personalityManaged||c)&&a?h.jsx(CE,{onLoad:a,...l?{onSave:l}:{},onDirtyChange:_,readOnly:p,title:p?"补充设定":"你的补充",hint:p?"这个 persona 的补充设定,由它的主人维护。与内置人格叠加生效。":"写入 <persona-dir>/.clawd/personality.local.md,不会被更新覆盖。与内置人格叠加生效,冲突时以你写的为准;对 owner 和访客会话都生效,要区分对象请在正文里写明。只对新启动的会话生效。",placeholder:"例:回答一律先给结论,再展开。",testIdPrefix:"persona-personality-local"}):null,h.jsx("hr",{className:"border-border"})]}):null,h.jsx(Gce,{settings:e.sandboxSettings??null}),h.jsx("hr",{className:"border-border"}),h.jsx(Yce,{skills:e.skills??[]}),h.jsx("hr",{className:"border-border"}),h.jsx(Xce,{plugins:e.plugins??[]})]})]})]}):null}function kE({qrUrl:e,busy:t,onCancel:n,title:r="扫码关联飞书 Bot",hint:i="用手机飞书扫码,按页面提示创建应用。确认后自动完成关联。"}){const[s,o]=g.useState(null);return g.useEffect(()=>{let a=!1;return ud.toDataURL(e,{width:240,margin:1}).then(l=>{a||o(l)}).catch(()=>{a||o(null)}),()=>{a=!0}},[e]),h.jsx(ej,{open:!0,onOpenChange:a=>a||n==null?void 0:n(),children:h.jsxs(Eb,{className:"max-w-xs","data-testid":"lark-bot-qr-dialog",onInteractOutside:a=>a.preventDefault(),onEscapeKeyDown:a=>a.preventDefault(),children:[h.jsx(nj,{children:h.jsx(Ib,{children:r})}),h.jsxs("div",{className:"flex flex-col items-center gap-2",children:[s?h.jsx("img",{src:s,alt:"飞书扫码创建应用二维码",className:"h-60 w-60 rounded bg-white p-2","data-testid":"lark-bot-qr-img"}):h.jsx("div",{className:"flex h-60 w-60 items-center justify-center text-[12px] text-text-400",children:"二维码生成中…"}),h.jsx("span",{className:"text-center text-[12px] text-text-300",children:i}),n?h.jsx("button",{type:"button",disabled:t,onClick:n,className:"rounded border border-border px-3 py-1.5 text-[12px] text-text-300 hover:bg-bg-200 disabled:opacity-50","data-testid":"lark-bot-provision-cancel",children:"取消"}):null]})]})})}const qce={expired:"二维码已过期,请重新扫码。",cancelled:"已取消。",access_denied:"你在飞书上取消了本次授权。",lark_protocol_error:"飞书返回了未预期的响应,请重试。",cloud_unreachable:"云端暂时不可达,请稍后重试。",internal_error:"关联失败。若飞书中已创建应用,可在开发者后台删除后重试,或改用手动绑定填入其凭证。"},Vce=new Set(["expired","access_denied","lark_protocol_error","cloud_unreachable","internal_error"]);function Kce({status:e,onProvision:t,onCancelProvision:n,onBindManual:r,onUnbind:i,onUpgrade:s,runtime:o="local"}){const[a,l]=g.useState(!1),[c,u]=g.useState(null),[d,f]=g.useState(""),[p,m]=g.useState(""),[x,w]=g.useState(null),v=N=>{N&&(l(!0),u(null),N().catch(E=>u(E instanceof Error?E.message:String(E))).finally(()=>l(!1)))},_=()=>{w(null),v(t)},b=!a&&!!d&&!!p,S=()=>{!b||!r||v(()=>r({appId:d,appSecret:p}))},C=Ju(S),k=h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx(Zp,{className:"h-3.5 w-3.5 text-text-400","aria-hidden":!0}),h.jsx("span",{className:"text-[13px] font-medium text-text-100",children:"飞书 Bot"})]});return e?h.jsxs("section",{className:"flex flex-col gap-1.5","data-testid":"lark-bot-section",children:[k,e.state==="unbound"||e.state==="provisioning"?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"text-[11px] text-text-400",children:["关联一个飞书 bot 后,这个 persona 就是它:拉进群后群成员 @ 它提问、或直接私聊它,",o==="cloud"?"云 Persona 在云端处理消息,回复自动发回去。":"推理跑在你本机,回复自动发回去。"]}),t?h.jsx("button",{type:"button",disabled:a||e.state==="provisioning",onClick:_,className:"self-start rounded border border-border bg-bg-200 px-3 py-1.5 text-[12px] font-medium text-text-100 hover:bg-bg-300 disabled:opacity-50","data-testid":"lark-bot-provision",children:e.state==="provisioning"?"等待扫码…":"扫码关联飞书 Bot"}):null,e.state==="unbound"&&e.errorReason&&!x?h.jsxs("div",{className:"flex flex-col gap-1.5 rounded border border-error bg-error-dim px-2 py-1.5","data-testid":"lark-bot-provision-error",children:[h.jsx("span",{className:"text-[11px] text-error",children:qce[e.errorReason]}),h.jsxs("div",{className:"flex gap-1.5",children:[Vce.has(e.errorReason)&&t?h.jsx("button",{type:"button",disabled:a,onClick:_,className:"rounded border border-border px-2 py-1 text-[11px] text-text-100 hover:bg-bg-200 disabled:opacity-50","data-testid":"lark-bot-provision-retry",children:"重新扫码"}):null,h.jsx("button",{type:"button",onClick:()=>w(e.errorReason??null),className:"rounded border border-border px-2 py-1 text-[11px] text-text-300 hover:bg-bg-200","data-testid":"lark-bot-provision-error-dismiss",children:"知道了"})]})]}):null,e.state==="provisioning"&&e.qrUrl?h.jsx(kE,{qrUrl:e.qrUrl,busy:a,onCancel:n?()=>v(n):void 0}):null,r&&e.state==="unbound"?h.jsxs("details",{"data-testid":"lark-bot-manual-details",children:[h.jsx("summary",{className:"cursor-pointer text-[11px] text-text-400 hover:text-text-300",children:"已有飞书应用?手动填入凭证"}),h.jsxs("div",{className:"mt-1.5 flex flex-col gap-1.5","data-testid":"lark-bot-manual-form",children:[h.jsx("span",{className:"text-[11px] text-text-400",children:"先在飞书开放平台(open.feishu.cn)创建企业自建应用并启用机器人能力,再填入凭证:"}),h.jsx("input",{value:d,onChange:N=>f(N.target.value),...C,placeholder:"App ID(cli_ 开头)",className:"rounded border border-border bg-bg-100 px-2 py-1 text-[12px] text-text-200","data-testid":"lark-bot-manual-appid"}),h.jsx("input",{value:p,onChange:N=>m(N.target.value),...C,type:"password",placeholder:"App Secret",className:"rounded border border-border bg-bg-100 px-2 py-1 text-[12px] text-text-200","data-testid":"lark-bot-manual-secret"}),h.jsx("button",{type:"button",disabled:!b,onClick:S,className:"self-start rounded border border-border px-3 py-1.5 text-[12px] text-text-100 hover:bg-bg-200 disabled:opacity-50","data-testid":"lark-bot-manual-submit",children:a?"绑定中…":"绑定"})]})]}):null]}):null,e.state==="bound"||e.state==="broken"?h.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.state==="bound"&&e.needsUpgrade?h.jsxs("div",{className:"flex flex-col gap-1.5 rounded border border-warning/30 bg-warning-dim px-2 py-1.5","data-testid":"lark-bot-upgrade-notice",children:[h.jsx("span",{className:"text-[11px] text-warning",children:"这个 bot 的权限配置有更新,扫码重新授权后生效。在此之前,新增能力对它不起作用。"}),s?h.jsx("button",{type:"button",disabled:a,onClick:()=>v(s),className:"self-start rounded border border-warning/30 bg-warning/10 px-2 py-1 text-[11px] text-warning hover:bg-warning/20 disabled:opacity-50","data-testid":"lark-bot-upgrade",children:"更新授权"}):null]}):null,e.state==="bound"&&e.upgradeQrUrl?h.jsx(kE,{qrUrl:e.upgradeQrUrl,busy:a,onCancel:n?()=>v(n):void 0,title:"扫码更新授权",hint:"用手机飞书扫码,确认页会列出将要添加的权限。期间 bot 照常服务,不会中断。"}):null,e.state==="broken"?h.jsxs("div",{className:"rounded border border-error bg-error-dim px-2 py-1.5 text-[11px] text-error","data-testid":"lark-bot-broken",children:["Bot 凭证失效:",e.brokenReason??"未知原因","。请解绑后重新填入有效凭证绑定。"]}):null,h.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-text-200",children:[h.jsx("span",{className:"font-medium text-text-100",children:e.botName??"未命名 bot"}),e.appId?h.jsx("span",{className:"text-[11px] text-text-400",children:e.appId}):null]}),h.jsx("span",{className:"text-[11px] text-text-400",children:"把 bot 拉进任意飞书群,群成员 @ 它即可提问。"}),e.groups.length>0?h.jsx("ul",{className:"flex flex-col gap-0.5","data-testid":"lark-bot-groups",children:e.groups.map(N=>h.jsxs("li",{className:"text-[11px] text-text-300 truncate",children:["· ",N.chatName??N.chatId]},N.chatId))}):h.jsx("span",{className:"text-[11px] text-text-400","data-testid":"lark-bot-groups-empty",children:"还没有服务中的群。"}),i?h.jsx("button",{type:"button",disabled:a,onClick:()=>v(i),className:"self-start rounded border border-border px-3 py-1.5 text-[12px] text-error hover:bg-error-dim disabled:opacity-50","data-testid":"lark-bot-unbind",children:"解绑"}):null]}):null,c?h.jsx("div",{className:"rounded border border-error bg-error-dim px-2 py-1.5 text-[11px] text-error","data-testid":"lark-bot-error",children:c}):null]}):h.jsxs("section",{className:"flex flex-col gap-1.5","data-testid":"lark-bot-section",children:[k,h.jsx("span",{className:"text-[11px] text-text-400",children:"状态加载中…"})]})}function Gce({settings:e}){var t,n,r,i,s,o,a,l,c,u,d,f,p;return h.jsxs("section",{className:"flex flex-col gap-2","data-testid":"persona-sandbox-setting-section",children:[h.jsxs("header",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-[13px] font-medium text-text-100",children:"Sandbox Setting"}),h.jsx("span",{className:"text-[11px] text-text-400",children:"约束此 persona 的沙箱权限(只读,需通过文件修改)。"})]}),e==null?h.jsx("span",{className:"text-[12px] text-text-300","data-testid":"persona-sandbox-setting-empty",children:"暂无 sandbox 配置"}):h.jsxs("div",{className:"flex flex-col gap-1.5 rounded-md border border-border bg-bg-100 px-3 py-2",children:[h.jsx(vh,{label:"权限默认模式",value:((t=e.permissions)==null?void 0:t.defaultMode)??"—"}),h.jsx(vh,{label:"沙箱启用",value:w0((n=e.sandbox)==null?void 0:n.enabled)}),h.jsx(vh,{label:"沙箱内自动放行 Bash",value:w0((r=e.sandbox)==null?void 0:r.autoAllowBashIfSandboxed)}),h.jsx(vh,{label:"允许非沙箱命令",value:w0((i=e.sandbox)==null?void 0:i.allowUnsandboxedCommands)}),h.jsxs("div",{className:"mt-1 flex flex-col gap-1.5 border-t border-border pt-1.5",children:[h.jsx(vc,{label:"沙箱外命令",paths:(s=e.sandbox)==null?void 0:s.excludedCommands}),h.jsx(vc,{label:"允许读取",paths:(a=(o=e.sandbox)==null?void 0:o.filesystem)==null?void 0:a.allowRead}),h.jsx(vc,{label:"拒绝读取",paths:(c=(l=e.sandbox)==null?void 0:l.filesystem)==null?void 0:c.denyRead}),h.jsx(vc,{label:"允许写入",paths:(d=(u=e.sandbox)==null?void 0:u.filesystem)==null?void 0:d.allowWrite}),h.jsx(vc,{label:"拒绝写入",paths:(p=(f=e.sandbox)==null?void 0:f.filesystem)==null?void 0:p.denyWrite})]})]})]})}function w0(e){return e===!0?"是":e===!1?"否":"—"}function vh({label:e,value:t}){return h.jsxs("div",{className:"flex items-center justify-between gap-3 text-[12px]",children:[h.jsx("span",{className:"text-text-300",children:e}),h.jsx("span",{className:"font-mono text-text-100",children:t})]})}function vc({label:e,paths:t}){const n=!t||t.length===0;return h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsx("span",{className:"text-[11px] text-text-300",children:e}),n?h.jsx("span",{className:"text-[11px] text-text-400",children:"—"}):h.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((r,i)=>h.jsx("span",{className:"rounded-sm border border-border bg-bg-0 px-1.5 py-0.5 font-mono text-[11px] text-text-200",children:r},`${e}-${i}-${r}`))})]})}function Yce({skills:e}){return h.jsxs("section",{className:"flex flex-col gap-2","data-testid":"persona-skills-section",children:[h.jsxs("header",{className:"flex flex-col gap-0.5",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-[13px] font-medium text-text-100",children:"Persona Skills"}),h.jsx("span",{className:"rounded-sm border border-border px-1.5 py-0.5 text-[10px] text-text-300",children:e.length})]}),h.jsxs("span",{className:"text-[11px] text-text-400",children:["此 persona 私有 skills(来自"," ",h.jsx("code",{className:"font-mono",children:"<persona-dir>/.claude/skills/"}),")。"]})]}),e.length===0?h.jsx("span",{className:"text-[12px] text-text-300","data-testid":"persona-skills-empty",children:"暂无 skills"}):h.jsx("ul",{className:"flex flex-col divide-y divide-border rounded-md border border-border bg-bg-100",children:e.map(t=>h.jsxs("li",{className:"flex flex-col gap-0.5 px-3 py-2","data-testid":"persona-skill-row",children:[h.jsx("span",{className:"font-mono text-[13px] text-text-100",children:t.name}),t.description?h.jsx("span",{className:"text-[12px] text-text-300",children:t.description}):h.jsx("span",{className:"text-[11px] text-text-400 italic",children:"无描述"})]},t.name))})]})}function Xce({plugins:e}){return h.jsxs("section",{className:"flex flex-col gap-2","data-testid":"persona-plugins-section",children:[h.jsxs("header",{className:"flex flex-col gap-0.5",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-[13px] font-medium text-text-100",children:"Enabled Plugins"}),h.jsx("span",{className:"rounded-sm border border-border px-1.5 py-0.5 text-[10px] text-text-300",children:e.length})]}),h.jsxs("span",{className:"text-[11px] text-text-400",children:["此 persona 已启用的插件(来自"," ",h.jsx("code",{className:"font-mono",children:"<persona-dir>/.claude/settings.json"})," ","的 ",h.jsx("code",{className:"font-mono",children:"enabledPlugins"}),")。"]})]}),e.length===0?h.jsx("span",{className:"text-[12px] text-text-300","data-testid":"persona-plugins-empty",children:"暂无启用插件"}):h.jsx("ul",{className:"flex flex-col divide-y divide-border rounded-md border border-border bg-bg-100",children:e.map(t=>h.jsx("li",{className:"flex flex-col gap-0.5 px-3 py-2","data-testid":"persona-plugin-row",children:h.jsx("span",{className:"font-mono text-[13px] text-text-100",children:t.id})},t.id))})]})}function CE({onLoad:e,onSave:t,onDirtyChange:n,initialPersonality:r,readOnly:i=!1,title:s,hint:o,placeholder:a,testIdPrefix:l}){const c=r!==void 0,[u,d]=g.useState(c),[f,p]=g.useState(c?r:""),[m,x]=g.useState(c?r:""),[w,v]=g.useState(null),[_,b]=g.useState(!1),[S,C]=g.useState(null),k=Qe.useRef(e),N=Qe.useRef(t),E=Qe.useRef(n);Qe.useEffect(()=>{k.current=e,N.current=t,E.current=n});const j=Qe.useCallback(()=>{d(!1),v(null),k.current().then(M=>{p(M),x(M),d(!0)}).catch(M=>{v(M instanceof Error?M.message:String(M))})},[]);Qe.useEffect(()=>{c||j()},[c,j]);const P=!i&&u&&m!==f;Qe.useEffect(()=>{i||E.current(P)},[P,i]);const D=()=>{N.current&&(b(!0),C(null),N.current(m).then(()=>{p(m),b(!1)}).catch(M=>{C(M instanceof Error?M.message:String(M)),b(!1)}))},R=()=>{x(f),C(null)},A=Ju(()=>{!P||_||D()},()=>{!P||_||R()});return h.jsxs("section",{className:"flex flex-col gap-2","data-testid":`${l}-section`,children:[h.jsx("span",{className:"text-[12px] font-medium text-text-200",children:s}),w?h.jsxs("div",{"data-testid":`${l}-load-error`,className:"rounded-md border border-error bg-error-dim px-3 py-2 text-[12px] text-error flex items-center justify-between gap-2",children:[h.jsxs("span",{children:["加载失败:",w]}),h.jsx("button",{type:"button",onClick:j,className:"rounded-sm border border-error px-2 py-0.5 text-[11px] hover:bg-error/10",children:"重试"})]}):null,S?h.jsxs("div",{"data-testid":`${l}-save-error`,className:"rounded-md border border-error bg-error-dim px-3 py-2 text-[12px] text-error",children:["保存失败:",S]}):null,h.jsx("textarea",{"data-testid":`${l}-textarea`,value:m,onChange:M=>x(M.target.value),...A,readOnly:i,disabled:!i&&(!u||_),placeholder:u?a??"":"加载中…",rows:8,className:"min-h-[8rem] max-h-[18rem] resize-y rounded-md border border-border bg-bg-100 px-2 py-1.5 font-mono text-[11px] text-text-100 disabled:opacity-60"}),o?h.jsx("p",{className:"text-[10px] text-text-400",children:o}):i?null:h.jsx("p",{className:"text-[10px] text-text-400",children:"写入人格文件。修改只对新启动的会话生效。"}),u&&P?h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{type:"button",onClick:R,disabled:_,className:"rounded-sm border border-border px-2 py-1 text-[12px] text-text-200 hover:bg-bg-200 disabled:opacity-60",children:"放弃"}),h.jsx("button",{type:"button",onClick:D,disabled:_,"data-testid":`${l}-save-btn`,className:"rounded-sm bg-accent-dim px-2 py-1 text-[12px] text-text-100 hover:opacity-90 disabled:opacity-60",children:_?"保存中…":"保存"})]}):null]})}const Zce={state:"unbound",groups:[]};function Qce(e,t,n="local"){const[r,i]=g.useState(null),s=d=>`${n==="cloud"?"cloud:":""}larkBot:${d}`;g.useEffect(()=>{if(!e)return;let d=!1,f=0,p=!1;i(null);const m=async()=>{const _=++f;p=!0;try{const b=await e.request(s("status"),{personaId:t});if(d||_!==f)return;i(S=>n==="cloud"&&(S!=null&&S.upgradeQrUrl)&&b.state==="bound"&&b.needsUpgrade!==!1?{...b,upgradeQrUrl:S.upgradeQrUrl}:b.state==="unbound"&&!b.errorReason&&(S==null?void 0:S.state)==="unbound"&&S.errorReason?{...b,errorReason:S.errorReason}:b)}catch{!d&&_===f&&i(b=>b??Zce)}finally{_===f&&(p=!1)}};m();const x=e.on("larkBot:state",_=>{const b=_;if(b.personaId!==t)return;const{personaId:S,...C}=b;++f,p=!1,i(C)}),w=e.on("daemon:connected",()=>{m()}),v=n==="cloud"?setInterval(()=>{p||m()},5e3):null;return()=>{d=!0,v&&clearInterval(v),x(),w()}},[e,t,n]);const o=g.useCallback(async()=>{e&&await e.request(s("provision"),{personaId:t})},[e,t,n]),a=g.useCallback(async()=>{e&&await e.request(s("provisionCancel"),{personaId:t})},[e,t,n]),l=g.useCallback(async d=>{e&&await e.request(s("bindManual"),{personaId:t,...d})},[e,t,n]),c=g.useCallback(async()=>{e&&await e.request(s("upgrade"),{personaId:t})},[e,t,n]),u=g.useCallback(async()=>{e&&await e.request(s("unbind"),{personaId:t})},[e,t,n]);return{status:r,provision:o,cancelProvision:a,bindManual:l,unbind:u,upgrade:c}}function Jce(e,t="owner"){var N;const{persona:n}=ZT(e),r=Oz(e),i=Bz(),s=$z(),{httpBaseUrl:o}=Yp(),a=Ni(),l=Qce(t==="guest"?null:a,e),{capabilities:c}=Im((n==null?void 0:n.tool)??"claude"),u=g.useMemo(()=>!(n!=null&&n.public)||!o||/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[?::1\]?)([:/]|$)/i.test(o)?null:`${o}/s/${e}`,[n==null?void 0:n.public,o,e]),d=g.useCallback((E,j)=>{i(e,j).catch(P=>{Oe("persona",`${E} failed`,P)})},[i,e]),f=g.useCallback(E=>d("togglePublic",{public:E}),[d]),p=g.useCallback(async E=>{await i(e,{codexSandbox:{network:E}}),await r.refresh()},[i,e,r]),m=g.useCallback(E=>d("changeTool",{tool:E}),[d]),x=g.useCallback(E=>d("changeModel",{model:E}),[d]),w=g.useCallback(E=>d("changeEffort",{effort:E}),[d]),v=g.useCallback(E=>d("toggleFastMode",{serviceTier:E?Bf.fast:Bf.standard}),[d]),_=g.useCallback(()=>!n||!confirm(`删除 persona "${n.label}"?`)?!1:(s(e).catch(E=>{Oe("persona","delete failed",E)}),!0),[n,s,e]),b=g.useCallback(async()=>r.loaded?r.personality:(await r.refresh()).personality,[r]),S=g.useCallback(async E=>{await i(e,{personality:E}),await r.refresh()},[i,e,r]),C=g.useCallback(async()=>r.loaded?r.personalityLocal:(await r.refresh()).personalityLocal,[r]),k=g.useCallback(async E=>{await i(e,{personalityLocal:E}),await r.refresh()},[i,e,r]);return{persona:n,detail:r,configSchema:(c==null?void 0:c.configSchema)??[],larkBot:l,guestShareUrl:u,changeTool:m,changeModel:x,changeEffort:w,toggleFastMode:v,togglePublic:f,guestNetwork:((N=r.codexSandbox)==null?void 0:N.network)??!1,toggleGuestNetwork:p,remove:_,loadPersonality:b,savePersonality:S,loadPersonalityLocal:C,savePersonalityLocal:k}}function eue({personaId:e,open:t,onClose:n,api:r,embedded:i,onDirtyChange:s,onShareCapability:o,viewerRole:a="owner"}){const l=Jce(e,a),{persona:c,detail:u}=l,d=g.useCallback(()=>{l.remove()&&n()},[l,n]);if(!c)return null;const f=a==="guest";return h.jsx(Wce,{embedded:i,persona:{...c,skills:u.skills,plugins:u.plugins,sandboxSettings:u.sandboxSettings,personalityManaged:u.personalityManaged},open:t,onClose:n,onLoadPersonality:l.loadPersonality,onLoadPersonalityLocal:l.loadPersonalityLocal,hasPersonalityLocal:u.personalityLocal!=="",onDirtyChange:s,readOnly:f,...f?{}:{onTogglePublic:l.togglePublic,guestShareUrl:l.guestShareUrl,onChangeTool:l.changeTool,onChangeModel:l.changeModel,onChangeEffort:l.changeEffort,configSchema:l.configSchema,onDelete:d,onSavePersonality:l.savePersonality,onSavePersonalityLocal:l.savePersonalityLocal,larkBot:{status:l.larkBot.status,onProvision:l.larkBot.provision,onCancelProvision:l.larkBot.cancelProvision,onBindManual:l.larkBot.bindManual,onUnbind:l.larkBot.unbind,onUpgrade:l.larkBot.upgrade},...o?{onShareCapability:o}:{}}})}const tue={resolve:()=>{}},nue=g.createContext(tue);function rue(){return g.useContext(nue)}const iue={...Qs,h1:({node:e,...t})=>h.jsx("h1",{...t,className:"mt-4 mb-3 text-[18px] font-semibold leading-tight text-text-100"}),h2:({node:e,...t})=>h.jsx("h2",{...t,className:"mt-4 mb-2 text-[16px] font-semibold leading-tight text-text-100"}),h3:({node:e,...t})=>h.jsx("h3",{...t,className:"mt-3 mb-2 text-[14px] font-semibold leading-tight text-text-100"}),h4:({node:e,...t})=>h.jsx("h4",{...t,className:"mt-3 mb-1 text-[13px] font-semibold text-text-100"}),h5:({node:e,...t})=>h.jsx("h5",{...t,className:"mt-2 mb-1 text-[12px] font-semibold text-text-100"}),h6:({node:e,...t})=>h.jsx("h6",{...t,className:"mt-2 mb-1 text-[12px] font-semibold text-text-300"}),p:({node:e,...t})=>h.jsx("p",{...t,className:"my-2 leading-relaxed"}),ul:({node:e,...t})=>h.jsx("ul",{...t,className:"my-2 list-disc space-y-1 pl-5"}),ol:({node:e,...t})=>h.jsx("ol",{...t,className:"my-2 list-decimal space-y-1 pl-5"}),li:({node:e,...t})=>h.jsx("li",{...t,className:"leading-relaxed"}),blockquote:({node:e,...t})=>h.jsx("blockquote",{...t,className:"my-2 border-l-2 border-border pl-3 italic text-text-300"}),code:({node:e,className:t,children:n,...r})=>t?h.jsx("code",{...r,className:`${t} font-mono text-[12px]`,children:n}):h.jsx("code",{...r,className:"rounded bg-bg-50 px-1 py-0.5 font-mono text-[12px] text-text-100",children:n}),pre:({node:e,...t})=>h.jsx("pre",{...t,className:"my-2 overflow-auto rounded border border-border bg-bg-0 p-3 text-[12px] font-mono text-text-100"}),hr:({node:e,...t})=>h.jsx("hr",{...t,className:"my-3 border-border"}),table:({node:e,...t})=>h.jsx("table",{...t,className:"my-2 w-full border-collapse text-[12px]"}),thead:({node:e,...t})=>h.jsx("thead",{...t,className:"bg-bg-50"}),th:({node:e,...t})=>h.jsx("th",{...t,className:"border border-border px-2 py-1 text-left font-semibold"}),td:({node:e,...t})=>h.jsx("td",{...t,className:"border border-border px-2 py-1"}),strong:({node:e,...t})=>h.jsx("strong",{...t,className:"font-semibold text-text-100"}),em:({node:e,...t})=>h.jsx("em",{...t,className:"italic"})};function sue(e){const t=e.split("/");return t[t.length-1]||e}function ij({relPath:e,loadMarkdown:t,headerRight:n,showTitleBar:r=!1}){const[i,s]=g.useState(null),[o,a]=g.useState(null),[l,c]=g.useState(!1);return g.useEffect(()=>{if(!e)return;let u=!1;return c(!0),a(null),s(null),(async()=>{try{const d=await t(e);if(u)return;s(d)}catch(d){if(u)return;a(d.message||String(d))}finally{u||c(!1)}})(),()=>{u=!0}},[e,t]),h.jsxs("div",{className:"flex flex-col h-full",children:[r&&e?h.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[h.jsx("div",{"data-testid":"md-preview-title",className:"truncate text-[13px] font-medium text-text-100",title:e,children:sue(e)}),h.jsx("div",{className:"flex items-center gap-1",children:n})]}):null,h.jsx("div",{className:"flex-1 overflow-auto px-4 py-3 text-[13px] text-text-100",children:l?h.jsx("div",{"data-testid":"md-preview-loading",className:"text-text-400",children:"Loading…"}):o?h.jsx("div",{"data-testid":"md-preview-error",className:"text-destructive whitespace-pre-wrap",children:o}):i!==null?h.jsx("div",{"data-testid":"md-preview-content",className:"max-w-none",children:h.jsx(xl,{remarkPlugins:[yl],components:iue,children:i})}):null})]})}function oue({open:e,onOpenChange:t,relPath:n,loadMarkdown:r,onShare:i}){return e?h.jsx("div",{"data-testid":"md-preview-drawer",className:`${ab} z-50 flex w-1/2 max-w-[900px] flex-col border-l border-border bg-elevated shadow-2xl`,children:h.jsx(ij,{relPath:n,loadMarkdown:r,showTitleBar:!0,headerRight:h.jsxs(h.Fragment,{children:[i?h.jsx("button",{type:"button","data-testid":"md-preview-share","aria-label":"Share rendered preview link",onClick:i,className:"inline-flex h-6 w-6 items-center justify-center rounded text-text-400 hover:bg-bg-50 hover:text-text-200",children:h.jsx(eF,{className:"h-4 w-4"})}):null,h.jsx("button",{type:"button","aria-label":"Close preview",onClick:()=>t(!1),className:"inline-flex h-6 w-6 items-center justify-center rounded text-text-400 hover:bg-bg-50 hover:text-text-200",children:h.jsx(Qr,{className:"h-4 w-4"})})]})})}):null}const EE=4;function aue({children:e,onHeightChange:t}){const n=g.useRef(null),[r,i]=g.useState(0);return g.useEffect(()=>{const s=n.current;if(!s)return;const o=()=>i(s.offsetHeight>0?s.offsetHeight+EE*2:0);if(o(),typeof ResizeObserver>"u")return;const a=new ResizeObserver(o);return a.observe(s),()=>a.disconnect()},[]),g.useEffect(()=>{t==null||t(r)},[r,t]),h.jsx("div",{"data-testid":"chat-floating-dock","data-height":r,className:"relative z-20 h-0 shrink-0",children:h.jsx("div",{ref:n,className:"absolute left-4 right-4 flex flex-col items-end gap-1",style:{bottom:EE},children:e})})}function lue(e,t,n,r,i,s){const[o,a]=g.useState(null),[l,c]=g.useState(i??null),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(null),w=g.useRef({api:e,sessionId:t,enabled:n,epoch:0,read:null,again:!1,mutating:!1}),v=g.useRef({api:e,sessionId:t,enabled:n});v.current={api:e,sessionId:t,enabled:n};const _=g.useRef(t),b=g.useRef(async()=>{}),S=N=>{if(N.workspace!==void 0&&a(N.workspace),N.binding!==void 0)c(N.binding);else if(N.workspace){const{workspaceId:E,repoId:j,owner:P,name:D,sourceBranch:R,defaultBranch:A}=N.workspace;c({workspaceId:E,repoId:j,owner:P,name:D,sourceBranch:R,defaultBranch:A})}},C=g.useCallback(async()=>{const N=w.current;if(!n||N.sessionId!==t||N.api!==e)return;if(N.mutating){N.again=!0;return}if(N.read)return N.again=!0,N.read;const E=N.epoch;d(!0);const j=(async()=>{try{const P=await e.cloudWorkspace({sessionId:t,action:"status"});w.current===N&&N.epoch===E&&v.current.sessionId===t&&(S(P),x(null))}catch(P){w.current===N&&N.epoch===E&&x(P.message)}finally{w.current===N&&(N.read=null,d(!1),N.again&&!N.mutating&&(N.again=!1,b.current()))}})();return N.read=j,j},[e,t,n]);b.current=C;const k=g.useCallback(async N=>{const E=w.current;if(!n||E.sessionId!==t)throw new Error("Cloud workspace unavailable");const j=N.action==="bind",P=["repositories","branches"].includes(N.action);if(j&&E.mutating)throw new Error("工作区操作正在进行");j&&(E.mutating=!0,E.epoch++,E.again=!1,p(!0),x(null));try{const D=await e.cloudWorkspace({...N,sessionId:t});return w.current===E&&v.current.sessionId===t&&(S(D),P||x(null)),D}catch(D){throw w.current===E&&!P&&x(D.message),D}finally{j&&w.current===E&&(E.mutating=!1,p(!1),(N.action==="bind"||E.again)&&(E.again=!1,b.current()))}},[e,t,n]);return g.useEffect(()=>{const N={api:e,sessionId:t,enabled:n,epoch:0,read:null,again:!1,mutating:!1};return w.current=N,_.current!==t&&(_.current=t,a(null),c(i??null)),x(null),p(!1),d(!1),n&&b.current(),()=>{N.epoch++,w.current===N&&(w.current={...N,enabled:!1,again:!1})}},[e,t,n]),g.useEffect(()=>{if(!(!n||!r))return r.on("session:event",N=>{var j;const E=N;E.sessionId===t&&["tool_result","turn_end","session_init"].includes(((j=E.event)==null?void 0:j.kind)??"")&&b.current()})},[r,t,n]),{workspace:o,binding:l,branchIntent:s,loading:u,busy:f,error:m,refresh:C,run:k}}var Am="Popover",[sj]=ro(Am,[Fl]),hd=Fl(),[cue,ao]=sj(Am),oj=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,a=hd(t),l=g.useRef(null),[c,u]=g.useState(!1),[d,f]=Bl({prop:r,defaultProp:i??!1,onChange:s,caller:Am});return h.jsx(sm,{...a,children:h.jsx(cue,{scope:t,contentId:bi(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:g.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:c,onCustomAnchorAdd:g.useCallback(()=>u(!0),[]),onCustomAnchorRemove:g.useCallback(()=>u(!1),[]),modal:o,children:n})})};oj.displayName=Am;var aj="PopoverAnchor",uue=g.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=ao(aj,n),s=hd(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:a}=i;return g.useEffect(()=>(o(),()=>a()),[o,a]),h.jsx(om,{...s,...r,ref:t})});uue.displayName=aj;var lj="PopoverTrigger",cj=g.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=ao(lj,n),s=hd(n),o=Ot(t,i.triggerRef),a=h.jsx(wt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":pj(i.open),...r,ref:o,onClick:Ie(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:h.jsx(om,{asChild:!0,...s,children:a})});cj.displayName=lj;var Nb="PopoverPortal",[due,hue]=sj(Nb,{forceMount:void 0}),uj=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=ao(Nb,t);return h.jsx(due,{scope:t,forceMount:n,children:h.jsx(Jr,{present:n||s.open,children:h.jsx(am,{asChild:!0,container:i,children:r})})})};uj.displayName=Nb;var El="PopoverContent",dj=g.forwardRef((e,t)=>{const n=hue(El,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=ao(El,e.__scopePopover);return h.jsx(Jr,{present:r||s.open,children:s.modal?h.jsx(pue,{...i,ref:t}):h.jsx(mue,{...i,ref:t})})});dj.displayName=El;var fue=fl("PopoverContent.RemoveScroll"),pue=g.forwardRef((e,t)=>{const n=ao(El,e.__scopePopover),r=g.useRef(null),i=Ot(t,r),s=g.useRef(!1);return g.useEffect(()=>{const o=r.current;if(o)return m_(o)},[]),h.jsx(cm,{as:fue,allowPinchZoom:!0,children:h.jsx(hj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ie(e.onCloseAutoFocus,o=>{var a;o.preventDefault(),s.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Ie(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,c=a.button===2||l;s.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:Ie(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),mue=g.forwardRef((e,t)=>{const n=ao(El,e.__scopePopover),r=g.useRef(!1),i=g.useRef(!1);return h.jsx(hj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var o,a;(o=e.onCloseAutoFocus)==null||o.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{var l,c;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(o))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),hj=g.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:o,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...d}=e,f=ao(El,n),p=hd(n);return i_(),h.jsx(em,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:h.jsx(Ku,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>f.onOpenChange(!1),children:h.jsx(f_,{"data-state":pj(f.open),role:"dialog",id:f.contentId,...p,...d,ref:t,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),fj="PopoverClose",gue=g.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=ao(fj,n);return h.jsx(wt.button,{type:"button",...r,ref:t,onClick:Ie(e.onClick,()=>i.onOpenChange(!1))})});gue.displayName=fj;var vue="PopoverArrow",xue=g.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=hd(n);return h.jsx(p_,{...i,...r,ref:t})});xue.displayName=vue;function pj(e){return e?"open":"closed"}var yue=oj,_ue=cj,bue=uj,mj=dj;const gj=yue,vj=_ue,Tb=g.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},i)=>h.jsx(bue,{children:h.jsx(mj,{ref:i,align:t,sideOffset:n,className:re("z-50 w-72 rounded-md border border-border bg-elevated p-4 text-text-100 shadow-md outline-none",e),...r})}));Tb.displayName=mj.displayName;const Wi="flex w-full min-w-0 items-center gap-2.5 rounded-md px-1.5 py-2 text-left text-[13px] hover:bg-text-100/5 disabled:opacity-40";function IE({title:e,children:t,trailing:n}){const[r,i]=g.useState(!0);return h.jsxs("section",{className:"rounded-xl border border-border bg-bg-0 p-3.5",children:[h.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[h.jsxs("button",{onClick:()=>i(!r),className:"flex items-center gap-1.5 py-0.5 text-[12px] font-medium text-text-200","aria-expanded":r,children:[e,h.jsx(Pn,{className:`h-3 w-3 text-text-400 ${r?"":"-rotate-90"}`})]}),n]}),r&&t]})}const wue=6e4,xj=300;function yj({message:e,onRetry:t}){return h.jsxs("div",{role:"alert",className:"m-2 rounded-md bg-error/5 p-2 text-[11px] leading-relaxed text-error",children:[e,h.jsx("button",{className:"ml-2 underline",onClick:t,children:"重试"})]})}function _j({controller:e,compact:t=!1}){const{binding:n,run:r,busy:i}=e,[s,o]=g.useState(!1),[a,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState([]),[p,m]=g.useState(1),[x,w]=g.useState(!1),[v,_]=g.useState(!1),[b,S]=g.useState(null),[C,k]=g.useState(0),N=g.useRef(!1),E=g.useRef(new Map);return g.useEffect(()=>{if(a===c)return;const j=setTimeout(()=>{u(a),m(1)},xj);return()=>clearTimeout(j)},[a,c]),g.useEffect(()=>{if(!s||n)return;const j=c+"|"+p,P=M=>{w(M.hasMore),f(L=>p===1?M.repos:[...L,...M.repos])},D=E.current.get(j);S(null);const R=N.current;if(N.current=!1,D&&Date.now()-D.at<wue&&!R){P(D),_(!1);return}let A=!1;return _(!0),r({action:"repositories",page:p,search:c}).then(M=>{if(A)return;const L={at:Date.now(),repos:M.repositories??[],hasMore:M.hasMore??!1};E.current.set(j,L),P(L)}).catch(M=>{A||S(M.message)}).finally(()=>{A||_(!1)}),()=>{A=!0}},[s,n,c,p,C,r]),n?h.jsxs("button",{className:t?"flex min-w-0 items-center gap-1.5 text-[11px] text-text-300 hover:text-text-100":Wi,title:n.owner+"/"+n.name,"aria-label":"在 GitHub 查看仓库",onClick:()=>window.open(`https://github.com/${n.owner}/${n.name}`,"_blank","noopener"),children:[h.jsx(wg,{className:"h-4 w-4 shrink-0 text-text-400"}),h.jsx("span",{className:"truncate",children:n.name}),!t&&h.jsx(wu,{className:"ml-auto h-3 w-3 text-text-400"})]}):h.jsxs(gj,{open:s,onOpenChange:j=>{o(j),j||(m(1),l(""),u(""))},children:[h.jsx(vj,{asChild:!0,children:h.jsxs("button",{disabled:i,className:t?"flex items-center gap-1.5 text-[11px] text-text-300":Wi,"aria-label":"添加或选择仓库",children:[h.jsx(wg,{className:"h-4 w-4 text-text-400"}),h.jsx("span",{className:"flex-1",children:"添加 repo"}),!t&&h.jsx(o4,{className:"h-3.5 w-3.5 text-text-400"})]})}),h.jsxs(Tb,{align:"end",className:"w-[330px] p-1.5",children:[h.jsxs("div",{className:"flex items-center gap-2 border-b border-border p-2",children:[h.jsx(zf,{className:"h-3.5 w-3.5 text-text-400"}),h.jsx("input",{autoFocus:!0,"aria-label":"搜索仓库",placeholder:"搜索 GitHub 仓库…",value:a,onChange:j=>l(j.target.value),className:"w-full bg-transparent text-[12px] outline-none"})]}),h.jsxs("div",{className:"max-h-[340px] overflow-y-auto py-1",children:[d.map(j=>h.jsxs("button",{disabled:i,className:Wi,onClick:()=>{S(null),r({action:"bind",repoId:j.repoId,branch:j.defaultBranch}).then(()=>o(!1)).catch(P=>S(P.message))},children:[h.jsx(wg,{className:"h-4 w-4 shrink-0 text-text-400"}),h.jsxs("span",{className:"truncate text-[12px]",children:[j.owner,"/",j.name]})]},j.repoId)),b&&h.jsx(yj,{message:b,onRetry:()=>{N.current=!0,k(j=>j+1)}}),!v&&!b&&!d.length&&h.jsx("p",{className:"p-3 text-[12px] text-text-400",children:"没有找到仓库"}),v&&h.jsxs("div",{className:"flex items-center gap-2 p-3 text-[12px] text-text-400",children:[h.jsx(Tn,{className:"h-3 w-3 animate-spin"}),"正在读取…"]}),x&&!v&&h.jsx("button",{className:Wi,onClick:()=>m(j=>j+1),children:"加载更多"})]})]})]})}function bj({controller:e,compact:t=!1,disabled:n=!1}){const{binding:r,workspace:i,branchIntent:s,run:o,busy:a}=e,[l,c]=g.useState(!1),[u,d]=g.useState(""),[f,p]=g.useState(""),[m,x]=g.useState([]),[w,v]=g.useState(1),[_,b]=g.useState(),[S,C]=g.useState(),[k,N]=g.useState(!1),[E,j]=g.useState(!1),[P,D]=g.useState(null),[R,A]=g.useState(0),M=u.trim();g.useEffect(()=>{if(M===f)return;if(!M){p("");return}const O=setTimeout(()=>p(M),xj);return()=>clearTimeout(O)},[M,f]),g.useEffect(()=>{if(!l||!r||M!==f)return;let O=!1;return D(null),j(!0),o({action:"branches",repoId:r.repoId,...f?{search:f,..._?{cursor:_}:{}}:{page:w}}).then(I=>{O||(x(U=>(f?!_:w===1)?I.branches??[]:[...U,...I.branches??[]]),N(!!(I.hasMore&&(!f||I.nextCursor))),C(I.nextCursor))}).catch(I=>{O||D(I.message)}).finally(()=>{O||j(!1)}),()=>{O=!0}},[l,r==null?void 0:r.repoId,M,f,w,_,R,o]);const L=O=>{c(O),O||(d(""),p(""),x([]),v(1),b(void 0),C(void 0),N(!1),j(!1),D(null))},z=s??(i==null?void 0:i.actualBranch)??(i?"HEAD · "+i.head.slice(0,7):(r==null?void 0:r.sourceBranch)??"选择 branch"),F=[...new Set([...[...r?[r.defaultBranch]:[],...i!=null&&i.actualBranch?[i.actualBranch]:[],...(i==null?void 0:i.branches)??[]].filter(O=>O.toLowerCase().includes(M.toLowerCase())),...m])],$=O=>{const I=O===((i==null?void 0:i.actualBranch)??(r==null?void 0:r.sourceBranch));o(I?{action:"intend"}:{action:"intend",branch:O}).then(()=>{L(!1)}).catch(()=>{})};return h.jsxs(gj,{open:l,onOpenChange:L,children:[h.jsx(vj,{asChild:!0,children:h.jsxs("button",{className:t?"flex min-w-0 items-center gap-1.5 text-[11px] text-text-300 disabled:opacity-40":Wi,"aria-label":`选择分支,当前 ${z}`,disabled:a||n,children:[h.jsx(Su,{className:"h-3.5 w-3.5 shrink-0 text-text-400"}),h.jsx("span",{className:"truncate",children:z}),h.jsx(Pn,{className:"ml-auto h-3 w-3 shrink-0 text-text-400"})]})}),h.jsxs(Tb,{align:"end",className:"w-[280px] p-1.5",children:[h.jsxs("div",{className:"flex items-center gap-2 border-b border-border p-2",children:[h.jsx(zf,{className:"h-3.5 w-3.5 text-text-400"}),h.jsx("input",{autoFocus:!0,"aria-label":"搜索分支",placeholder:"搜索分支…",value:u,maxLength:100,onChange:O=>{d(O.target.value),O.target.value.trim()!==M&&(x([]),v(1),b(void 0),C(void 0),N(!1),D(null),j(!0))},className:"w-full bg-transparent text-[12px] outline-none"})]}),h.jsxs("div",{className:"max-h-[300px] overflow-y-auto",children:[(M===f?F:[]).map(O=>h.jsxs("button",{className:Wi,onClick:()=>$(O),children:[h.jsx(Su,{className:"h-3.5 w-3.5 text-text-400"}),h.jsx("span",{className:"flex-1 truncate",children:O}),O===(r==null?void 0:r.defaultBranch)&&h.jsx("span",{className:"text-[10px] text-text-400",children:"默认"}),O===z&&h.jsx(Zo,{className:"h-3.5 w-3.5"})]},O)),P&&h.jsx(yj,{message:P,onRetry:()=>A(O=>O+1)}),E&&h.jsxs("div",{role:"status",className:"flex items-center gap-2 p-3 text-[12px] text-text-400",children:[h.jsx(Tn,{className:"h-3 w-3 animate-spin"}),"正在读取…"]}),!E&&!P&&!F.length&&h.jsx("p",{className:"p-3 text-[12px] text-text-400",children:"没有找到分支"}),k&&h.jsx("button",{className:Wi,disabled:E||!!P,onClick:()=>{j(!0),f?b(S):v(O=>O+1)},children:"加载更多分支"})]})]})]})}function Sue({controller:e,disabled:t=!1}){return h.jsxs("div",{"data-testid":"workspace-input-chip",className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 px-1 pb-2 text-text-300",children:[h.jsx("div",{className:"max-w-[200px] min-w-0",children:h.jsx(_j,{controller:e,compact:!0})}),e.binding&&h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"h-3 w-px bg-border"}),h.jsx("div",{className:"min-w-0 max-w-[230px]",children:h.jsx(bj,{controller:e,compact:!0,disabled:t},e.binding.repoId)})]}),e.loading&&h.jsx(Tn,{className:"h-3 w-3 shrink-0 animate-spin text-text-400"})]})}function kue({controller:e,disabled:t=!1}){var x;const{binding:n,workspace:r,branchIntent:i,loading:s,busy:o,error:a,refresh:l,run:c}=e,[u,d]=g.useState(null),[f,p]=g.useState();g.useEffect(()=>{if(!u){p(void 0);return}let w=!1;return p(void 0),c({action:"diff",filePath:u}).then(v=>{w||p(v.diff)}).catch(()=>{}),()=>{w=!0}},[u,c]);const m=(x=r==null?void 0:r.files.find(w=>w.path===u))==null?void 0:x.comparison;return h.jsxs("div",{className:"space-y-3",children:[h.jsxs(IE,{title:"环境",trailing:h.jsx("button",{"aria-label":"刷新工作区",title:"刷新工作区",disabled:o||s,onClick:()=>void l(),className:"p-1 text-text-400 disabled:opacity-40",children:h.jsx(bF,{className:`h-3 w-3 ${s?"animate-spin":""}`})}),children:[h.jsxs("div",{className:"flex items-center gap-2.5 px-1.5 py-2 text-[13px]",children:[h.jsx(E7,{className:"h-4 w-4 text-text-400"}),h.jsx("span",{children:"云端"}),h.jsx("span",{className:"ml-auto text-[11px] text-text-400",children:n?"已关联":"待关联"})]}),h.jsx(_j,{controller:e}),n&&h.jsx(bj,{controller:e,disabled:t},n.repoId),i&&h.jsxs("p",{className:"mt-1 px-1.5 text-[11px] text-text-400",children:["将在下一条消息里让 agent 切换到 ",i]}),r&&h.jsxs("p",{className:"mt-1 px-1.5 text-[10px] text-text-400",children:["截至 ",FH(new Date(r.measuredAt).toISOString())," ·"," ",r.head.slice(0,7)]}),!n&&h.jsx("p",{className:"mt-2 px-1.5 text-[11px] leading-relaxed text-text-400",children:"关联仓库和分支,在这个会话的独立工作区里开发。"}),a&&h.jsxs("div",{role:"alert",className:"mt-2 rounded-md bg-error/5 p-2 text-[11px] leading-relaxed text-error",children:[a,h.jsx("button",{className:"ml-2 underline",onClick:()=>void l(),children:"重试读取"})]})]}),!!(r!=null&&r.files.length)&&h.jsxs(IE,{title:"Changes",trailing:h.jsxs("span",{className:"text-[10px] text-text-400",children:[r.totalFiles??r.files.length," 个文件"]}),children:[h.jsxs("button",{"aria-label":"查看全部改动",className:Wi,onClick:()=>d(r.files[0].path),children:[h.jsx(L7,{className:"h-4 w-4 text-text-400"}),h.jsxs("span",{className:"tabular-nums text-success",children:["+",r.added]}),h.jsxs("span",{className:"tabular-nums text-error",children:["−",r.removed]}),h.jsx(e4,{className:"ml-auto h-3 w-3 text-text-400"})]}),h.jsx("div",{className:"mb-2",children:r.files.map(w=>h.jsxs("button",{className:"flex w-full min-w-0 items-center gap-2 rounded-md px-1.5 py-1.5 text-left text-[11px] hover:bg-text-100/5",onClick:()=>d(w.path),children:[h.jsx("span",{className:"w-4 shrink-0 text-[10px] text-text-400",children:w.status}),h.jsx("span",{title:w.path,className:"min-w-0 flex-1 truncate text-text-300",children:w.path.split("/").at(-1)}),h.jsxs("span",{className:"text-success",children:["+",w.added]}),h.jsxs("span",{className:"text-error",children:["−",w.removed]})]},w.path))}),r.filesTruncated&&h.jsx("p",{className:"mb-2 px-1 text-[11px] text-text-400",children:"仅展示前 200 个改动文件。"})]}),h.jsx(ej,{open:u!==null,onOpenChange:w=>{w||d(null)},children:h.jsxs(Eb,{className:"flex h-[min(680px,84vh)] w-[min(1080px,94vw)] max-w-none flex-col gap-0 overflow-hidden p-0",children:[h.jsxs("div",{className:"border-b border-border px-5 py-4",children:[h.jsx(Ib,{className:"text-[14px]",children:"代码改动"}),h.jsxs(rj,{className:"mt-2 text-[11px]",children:[(r==null?void 0:r.actualBranch)??"HEAD"," ·"," ",m==="index"?"暂存区相对当前提交的改动":m==="head"?"尚未提交的改动":"相对起始提交 "+(r==null?void 0:r.initialCommit.slice(0,7))+" 的累计改动"]})]}),h.jsxs("div",{className:"flex min-h-0 flex-1",children:[h.jsx("nav",{"aria-label":"改动文件",className:"w-[225px] shrink-0 overflow-auto border-r border-border bg-bg-50 p-2 max-[700px]:hidden",children:r==null?void 0:r.files.map(w=>h.jsx("button",{className:Wi+" text-[11px]",onClick:()=>d(w.path),children:h.jsx("span",{className:"truncate",children:w.path.split("/").at(-1)})},w.path))}),h.jsxs("div",{className:"min-w-0 flex-1 overflow-auto",children:[h.jsx("div",{className:"sticky top-0 border-b border-border bg-bg-50 px-4 py-3 font-mono text-[11px]",children:u}),f?f.binary?h.jsx("p",{className:"p-5 text-[12px] text-text-400",children:"二进制文件发生变化"}):f.notStored?h.jsx("p",{className:"p-5 text-[12px] text-text-400",children:"这个文件的补丁暂不可用(文件较多或体积较大时只保存部分补丁)。"}):h.jsxs("pre",{className:"min-w-fit py-2 font-mono text-[11px] leading-6",children:[f.patch.split(`
623
- `).map((w,v)=>h.jsx("div",{className:`px-4 ${w.startsWith("+")?"bg-success/8 text-success":w.startsWith("-")?"bg-error/8 text-error":"text-text-300"}`,children:w||" "},v)),f.truncated&&h.jsx("div",{className:"px-4 text-text-400",children:"Diff 较大,已截断显示。"})]}):h.jsx("div",{className:"p-5 text-[12px] text-text-400",children:a??"正在读取 diff…"})]})]})]})})]})}const Cue=250;function Eue(e){if(!e||!Number.isFinite(e))return null;const t=e/1e3;if(t<60)return`${t.toFixed(0)}s`;const n=Math.floor(t/60);return`${n}m${Math.round(t-n*60).toString().padStart(2,"0")}s`}function Iue({agents:e}){var l,c,u;const[t,n]=g.useState(!1),r=g.useRef(null);if(g.useEffect(()=>{if(!t)return;const d=f=>{const p=r.current;p&&f.target instanceof Node&&p.contains(f.target)||n(!1)};return window.addEventListener("pointerdown",d,!0),()=>window.removeEventListener("pointerdown",d,!0)},[t]),e.length===0)return null;const i=e.length===1?e[0]:null,s=i?i.description:`${e.length} 个后台任务`,o=i?Eue((c=(l=i.progress)==null?void 0:l.stats)==null?void 0:c.durationMs):null,a=i?(u=i.progress)==null?void 0:u.lastToolName:null;return h.jsxs("div",{ref:r,"data-testid":"running-agents-chip","data-agent-count":e.length,className:"relative",children:[t?h.jsx("div",{"data-testid":"running-agents-popover",className:"absolute bottom-full right-0 z-20 mb-1 w-[min(560px,80vw)]",children:h.jsx("div",{className:"min-w-0 overflow-y-auto rounded-lg border border-bg-200/60 bg-bg-100 px-2 py-1 shadow-lg",style:{maxHeight:Cue},children:e.map(d=>h.jsx(SM,{expandable:!1,description:d.description,input:d.input,output:d.output,...d.error!==void 0?{error:d.error}:{},pending:d.pending,notifications:d.notifications,...d.toolResultExtra?{toolResultExtra:d.toolResultExtra}:{},...d.progress?{progress:d.progress}:{}},d.toolUseId))})}):null,h.jsxs("button",{type:"button","data-testid":"running-agents-chip-toggle","aria-expanded":t,onClick:()=>n(d=>!d),className:re("flex max-w-[min(560px,80vw)] min-w-0 items-center gap-2 rounded-full","border border-bg-200/60 bg-bg-100/95 px-3 py-1 text-[12px] shadow-md backdrop-blur","hover:bg-bg-200/95 transition-colors"),children:[h.jsx(Tn,{className:"w-3 h-3 shrink-0 animate-spin text-blue-400"}),h.jsx("span",{className:"min-w-0 flex-1 truncate text-left text-text-200",children:s}),o?h.jsx("span",{className:"shrink-0 tabular-nums text-text-400",children:o}):null,a?h.jsxs("span",{className:"shrink-0 font-mono tabular-nums text-blue-400",children:["now:",a]}):null,h.jsx(t4,{className:re("w-3.5 h-3.5 shrink-0 text-text-400 transition-transform",t&&"rotate-180")})]})]})}const Nue={closeTrailing:!1},Tue={closeTrailing:!0};function Pue(e){return e?Nue:Tue}function Rue({session:e,api:t,onPromoteQuickAsk:n}){const r=KP(e.sessionId);return h.jsx(wj,{state:r,extras:{session:e,api:t,...n?{onPromoteQuickAsk:n}:{}}})}function Mue({headerMeta:e,connState:t,liveWorktreeRoot:n,onOpenConfig:r,variant:i="full",ephemeral:s,onPromote:o,hideHeader:a=!1,flatProcess:l=!1,lines:c,pendingPermissions:u,procAlive:d,rewindableUserMessageIds:f,onPermissionRespond:p,onPermissionInterrupt:m,onRewind:x,onFork:w,onQuickAsk:v,topSlot:_,codexHistory:b,realtimeQuestionAnswers:S,onSubmitQuestion:C,onCancelQuestion:k,liveQuestionToolUseIds:N,api:E,cwd:j,tool:P,cloudVolume:D,sessionKey:R,onSend:A,awaitingUser:M,queued:L,onDequeue:z,onAbort:F,onNewSession:$,onClearSession:O,configSlot:I,workspaceInput:U,workspaceInputDisabled:V,chatRootRef:B,chatBodyRef:ne,drawers:ae,xtermSlot:Y,fileSharingScope:ye,onShareFile:Ce,onOpenInTab:oe,onPreviewMarkdown:je,onOpenFilePath:Me,dispatchOrigin:De}){const[xe,Ke]=g.useState(0),rt=g.useMemo(()=>i==="full"?gY(XP(c)):[],[c,i]),Ze=g.useMemo(()=>new Set(rt.map(ht=>ht.toolUseId)),[rt]);return h.jsx(uie,{children:h.jsxs("div",{ref:B,"data-cc-chat-root":"",className:"flex flex-col h-full bg-bg-100",children:[a?null:h.jsx(lse,{meta:e,...P?{tool:P}:{},...D?{cloudVolume:D}:{},connState:t,variant:i,...n!==void 0?{liveWorktreeRoot:n}:{},...i==="full"&&r?{onOpenConfig:r}:{},...i==="quickask"?{ephemeral:s??!1,...o?{onPromote:o}:{}}:{}}),h.jsx("div",{ref:ne,"data-testid":"chat-body",className:"flex-1 overflow-y-auto min-h-0",style:{overflowAnchor:"none",paddingBottom:xe},children:h.jsx(CM,{lines:c,forkByTurn:P==="codex",...p?{onPermissionRespond:p}:{},...m&&d?{onPermissionInterrupt:m}:{},topSlot:_,codexHistory:b,...x?{onRewind:x}:{},rewindableUserMessageIds:f,...w?{onFork:w}:{},...v?{onQuickAsk:v}:{},realtimeQuestionAnswers:S,onSubmitQuestion:C,...k?{onCancelQuestion:k}:{},liveQuestionToolUseIds:N,...ye?{fileSharingScope:ye}:{},...Ce?{onShareFile:Ce}:{},...oe?{onOpenInTab:oe}:{},...je?{onPreviewMarkdown:je}:{},...Me?{onOpenFilePath:Me}:{},...De?{dispatchOrigin:De}:{},...i==="full"&&!l?{turnCollapse:Pue(d)}:{},dockedAgentToolUseIds:Ze})}),Y,h.jsx(aue,{onHeightChange:Ke,children:h.jsx(Iue,{agents:rt})}),e.larkChatName?h.jsx("div",{className:"mx-3 mb-3 rounded-lg border border-border bg-bg-200 px-3 py-2 text-[12px] text-text-400","data-testid":"lark-readonly-notice",children:e.larkChatType==="p2p"?`此会话由与「${e.larkChatName}」的飞书私聊驱动——对方消息触发,这里仅供观察。`:`此会话由飞书群「${e.larkChatName}」驱动——群成员 @ bot 提问触发,这里仅供观察。`}):h.jsx(ose,{meta:e,aboveSlot:U,disabled:V,...E?{api:E}:{},cwd:j,...P?{tool:P}:{},sessionKey:R,onSend:A,awaitingUser:M,...L?{queued:L}:{},...z?{onDequeue:z}:{},...F?{onAbort:F}:{},...$?{onNewSession:$}:{},...O?{onClearSession:O}:{},...I?{configSlot:I}:{}}),ae]})})}function wj({state:e,extras:t,onQuickAskInternal:n,onPreviewMdInternal:r}){var xr;const{session:i,api:s,liveGitBranch:o,liveWorktreeRoot:a,cloudVolume:l,onNewSession:c,onTurnEnd:u,onOpenConfig:d,onFork:f,onQuickAsk:p,viewerRole:m,onPromoteQuickAsk:x,configSlot:w,hideHeader:v,flatProcess:_}=t,{capabilities:b}=Im(i.tool||"claude"),S=(b==null?void 0:b.features)??VT(i.tool),[C,k]=g.useState(null),[N,E]=g.useState(null),j=Yp(),P=!!s&&j.actionsLevel==="owner"&&S.fileSharing,D=ZT(i.ownerPersonaId??null).persona,R=(D==null?void 0:D.label)??null,A=!!R&&!!i.ownerPersonaId,M=rue(),L=g.useMemo(()=>({resolve:(Z,we)=>M.resolve(Z,we,i.sessionId),...M.onOpenSession?{onOpenSession:M.onOpenSession}:{}}),[M,i.sessionId]),z=g.useCallback((Z,we)=>{k({kind:Z,text:we}),setTimeout(()=>{k(Ae=>(Ae==null?void 0:Ae.text)===we?null:Ae)},2e3)},[]),F=Ni(),$=ox(i.tool)&&m!=="guest"&&!i.larkChatId&&!x,O=lue(s,i.sessionId,$&&t.focused!==!1,F,i.cloudWorkspace,i.cloudBranchIntent),I=fz(),U=HP(i.sessionId,i.toolSessionId),{events:V,pendingQuestions:B,clearQuestion:ne,markQuestionSubmitted:ae,status:Y}=U,ye=e.historyLoading,Ce=VP(Y);g.useEffect(()=>{Oe("chat-panel","sessionStatus",{sessionId:i.sessionId,sessionStatus:Y,procAlive:Ce})},[Y,Ce,i.sessionId]);const oe=e.lines,je=e.pendingPermissions,Me=je[0]??null,De=g.useMemo(()=>pY(V),[V]),[xe,Ke]=g.useState(null),[rt,Ze]=g.useState(()=>new Set);dY(s,i.sessionId,i.toolSessionId,S.observe);const ht=g.useRef(i.sessionId);g.useEffect(()=>{if(ht.current=i.sessionId,!S.rewind){Ke(null);return}let Z=!1;return Ke(null),(async()=>{try{const we=await s.sessionRewindableMessageIds(i.sessionId);if(Z)return;Ke(new Set(we.userMessageIds))}catch{Z||Ke(null)}})(),()=>{Z=!0}},[s,i.sessionId,S.rewind]);const Kt=g.useCallback(()=>{const Z=i.sessionId;s.sessionRewindableMessageIds(Z).then(we=>{ht.current===Z&&Ke(new Set(we.userMessageIds))}).catch(()=>{})},[s,i.sessionId]),ue=g.useMemo(()=>{if(xe!==null){const lt=new Set(xe);for(const Or of rt)lt.delete(Or);return lt}const Z=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),we=new Set;let Ae=null;for(const lt of oe)lt.kind==="user-text"?Ae=lt.uuid??null:Ae&&lt.kind==="tool-call"&&Z.has(lt.tool)&&!rt.has(Ae)&&we.add(Ae);return we},[oe,rt,xe]),ze=g.useRef(u);ze.current=u,hY(i.sessionId,i.toolSessionId,()=>{hn(null),Ze(new Set)});const ke=kse({sessionStatus:Y}),Fe=g.useRef(null);g.useEffect(()=>{var Ae;const Z=Fe.current,we=(Z==null?void 0:Z.sid)===i.sessionId;we&&Z.phase===ke||(Fe.current={sid:i.sessionId,phase:ke},Oe("session-phase",ke,{sid:i.sessionId,phase:ke,prev:we?Z.phase:null,desc:Sse[ke]}),we&&Z.phase==="turn-running"&&ke!=="turn-running"&&((Ae=ze.current)==null||Ae.call(ze),Kt()))},[ke,i.sessionId,Kt]);const yt=g.useCallback(async()=>{const Z=await s.sessionInterrupt(i.sessionId).catch(()=>{});return(Z==null?void 0:Z.queued)??[]},[s,i.sessionId]),[tn,hn]=g.useState(null),W=g.useCallback(Z=>{hn(Z)},[]),[ee,be]=g.useState(!1),Le=g.useCallback(()=>{s.sessionStop(i.sessionId).catch(()=>{}),be(!1)},[s,i.sessionId]);g.useCallback(Z=>{s.pinSession(i.sessionId,Z).catch(we=>{Oe("chat-panel","pinSession failed",{err:we==null?void 0:we.message})})},[s,i.sessionId]);const He=x?"quickask":"full",{container:At,workspaceContainer:bn,onCollapse:nn,hostExtras:fn}=mse(),le=g.useRef(0),Se=g.useRef(null);g.useEffect(()=>{const Z=we=>{if(we.key!=="Escape")return;if(!Ce){le.current=0;return}if(we.isComposing)return;const lt=we.target;if(lt&&lt.closest("[data-cc-chat-root]")!==Se.current)return;const Or=Date.now();Or-le.current<2e3?(le.current=0,be(!0)):(le.current=Or,yt())};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[yt,Ce]);const it=g.useRef(null),mt=g.useRef(null),gr=g.useRef(!!e.codexHistory);gr.current=!!e.codexHistory;const se=g.useRef(!0),nt=g.useRef(void 0),Bt=g.useRef(0),ti=g.useRef(0),sa=g.useRef(void 0);g.useEffect(()=>{E(null)},[i.sessionId]),g.useEffect(()=>{const Z=it.current;if(!Z)return;const we=150,Ae=lt=>{gr.current||Date.now()<ti.current&&(lt.preventDefault(),ti.current=Date.now()+we)};return Z.addEventListener("wheel",Ae,{passive:!1}),()=>Z.removeEventListener("wheel",Ae)},[]),g.useEffect(()=>{const Z=it.current;if(!Z)return;const we=32,Ae=()=>{var Or;const lt=Z.scrollHeight-Z.scrollTop-Z.clientHeight;se.current=lt<=we,e.codexHistory&&(mt.current=p2(Z)),Z.scrollTop<=24&&e.historyHasMore&&!e.historyLoadingOlder&&!e.historyError&&!ye&&((Or=e.loadOlderHistory)==null||Or.call(e))};return Z.addEventListener("scroll",Ae,{passive:!0}),()=>Z.removeEventListener("scroll",Ae)},[e.codexHistory,e.historyHasMore,e.historyLoadingOlder,e.historyError,e.loadOlderHistory,ye]),g.useLayoutEffect(()=>{var Pb;const Z=it.current;if(!Z)return;const we=sa.current!==i.sessionId;we&&(sa.current=i.sessionId,se.current=!0,nt.current=void 0,Bt.current=0,ti.current=0,mt.current=null);const Ae=nt.current,lt=(Pb=oe[0])==null?void 0:Pb.seq;if(nt.current=lt,e.codexHistory){!we&&mt.current&&!se.current?Tie(Z,mt.current):se.current&&(Z.scrollTop=Z.scrollHeight),mt.current=p2(Z),Bt.current=Z.scrollHeight-Z.scrollTop;return}!we&&Ae!==void 0&&lt!==void 0&&lt<Ae?(Z.scrollTop=Z.scrollHeight-Bt.current,ti.current=Date.now()+200):se.current&&(Z.scrollTop=Z.scrollHeight),Bt.current=Z.scrollHeight-Z.scrollTop},[oe,Me==null?void 0:Me.requestId,i.sessionId]);const oa=g.useMemo(()=>{const Z={};for(const[we,Ae]of Object.entries(B))Ae.submittedAnswers&&(Z[we]=Ae.submittedAnswers);return Z},[B]),hs=g.useMemo(()=>new Set(Object.keys(B)),[B]),aa=g.useCallback(async(Z,we)=>{try{await s.answerQuestion({sessionId:i.sessionId,toolUseId:Z,answers:we}),ae(Z,we)}catch{}},[s,i.sessionId,ae]),Gl=g.useCallback(async Z=>{try{await s.cancelQuestion({sessionId:i.sessionId,toolUseId:Z}),ne(Z)}catch{}},[s,i.sessionId,ne]),Yl=g.useCallback(async(Z,we)=>{var Ae;if(Me)try{await((Ae=e.respondPermission)==null?void 0:Ae.call(e,Me.requestId,Z?"allow":"deny"))}catch{}},[e,Me]),fs=g.useCallback(async()=>{const Z=i.sessionId;try{await s.sessionStop(Z)}catch{}e.clearSession?await e.clearSession():await s.sessionNew(Z)},[e,s,i.sessionId]),ni=e.meta.streamInProgress??!1,fd=g.useMemo(()=>{if(e.codexHistory)return h.jsxs("div",{className:"flex flex-col items-center gap-2 py-2 text-xs text-text-400","data-testid":"codex-history-top",children:[e.historySyncError?h.jsx("span",{children:e.historySyncError}):null,e.historyError?h.jsx("span",{"data-testid":"history-error",children:e.historyError}):null,ye||e.historyLoadingOlder?h.jsx("span",{"data-testid":"history-loading",children:"正在加载历史…"}):e.historyHasMore?h.jsx("button",{type:"button",onClick:()=>{var we;return void((we=e.loadOlderHistory)==null?void 0:we.call(e))},children:e.historyError?"重试更早记录":"加载更早记录"}):e.historyLoaded&&!e.historyError&&!e.historySyncError?h.jsx("span",{children:"已加载全部轮次摘要"}):null,e.historyError||e.historySyncError?h.jsx("button",{type:"button",onClick:()=>{var we;return void((we=e.refreshHistory)==null?void 0:we.call(e))},children:"刷新历史"}):null]});const Z=e.historySyncError?h.jsxs("div",{className:"flex justify-center items-center gap-2 py-2 text-[12px] text-text-400","data-testid":"history-sync-error",children:[h.jsx("span",{children:e.historySyncError}),e.reloadFromCloud?h.jsx("button",{type:"button","data-testid":"history-sync-reload",disabled:ni,onClick:e.reloadFromCloud,className:"text-accent hover:underline cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 disabled:no-underline",children:"从云端重新加载"}):null]}):null;return e.historyError?h.jsxs(h.Fragment,{children:[Z,h.jsxs("div",{className:"flex justify-center py-2 text-[12px] text-text-400","data-testid":"history-error",children:["历史未加载完(",e.historyError,");切走再切回可重试"]})]}):Z||(ye&&oe.length===0?h.jsx("div",{className:"flex justify-center py-4","data-testid":"history-loading",children:h.jsx(Tn,{className:"w-4 h-4 text-text-400 animate-spin"})}):null)},[ye,oe.length,e.historyError,e.historySyncError,e.reloadFromCloud,ni,e.codexHistory,e.historyHasMore,e.historyLoaded,e.historyLoadingOlder,e.loadOlderHistory,e.refreshHistory]),la=e.meta,Gt=h.jsxs(h.Fragment,{children:[i.toolSessionId&&S.subagents?h.jsx(gse,{api:s,cwd:i.cwd,toolSessionId:i.toolSessionId,toolKind:i.tool??"claude"}):null,tn&&S.rewind?h.jsx(xse,{open:!0,onOpenChange:Z=>{Z||hn(null)},api:s,sessionId:i.sessionId,userMessageId:tn,lines:oe,procAlive:Ce,onNoChanges:Z=>{Ze(we=>{if(we.has(Z))return we;const Ae=new Set(we);return Ae.add(Z),Ae})}}):null,ee?h.jsx(Aue,{onConfirm:Le,onCancel:()=>be(!1)}):null]}),Xl={kind:"session",sessionId:i.sessionId},pd=g.useCallback(async Z=>{if(s)try{await dC(s,F,i.sessionId,Z)}catch(we){const Ae=we.message;Oe("chat-panel","open-in-tab failed",{err:Ae}),z("err",`Open in tab 失败:${Ae}`)}},[s,F,i.sessionId,z]),[jt,$t]=g.useState(!1),[Wn,vr]=g.useState(null),Mi=g.useCallback(Z=>{if(r){r(Z);return}vr(Z),$t(!0)},[r]),jm=g.useCallback(Z=>{if(!s)return;const we=async()=>{try{await s.attachmentGroupAdd(i.sessionId,Z)}catch(lt){Oe("chat-panel","file-link groupAdd skipped",{err:lt.message})}},Ae=lt=>{const Or=lt.message;Oe("chat-panel","file-link open failed",{err:Or}),z("err",`打开文件失败:${Or}`)};if(wm(Z)){we().then(()=>Mi(Z),Ae);return}dC(s,F,i.sessionId,Z,60,we).catch(Ae)},[s,F,i.sessionId,Mi,z]),md=g.useCallback(async Z=>{if(!s)throw new Error("daemon api not ready");const we=await F_(s,F,i.sessionId,Z,60),Ae=await fetch(we);if(!Ae.ok)throw new Error(`fetch ${Ae.status} ${Ae.statusText}`);return await Ae.text()},[s,F,i.sessionId]),lo=g.useCallback(async(Z,we)=>{if(s)try{const{url:Ae}=await s.attachmentSignUrl({sessionId:i.sessionId,relPath:Z,...we?{view:we}:{}}),lt=await JG(Ae);z(lt?"ok":"err",lt?"分享链接已复制到剪贴板":"复制失败:请手动复制")}catch(Ae){const lt=Ae.message;Oe("chat-panel","share-file failed",{err:lt}),z("err",`生成分享链接失败:${lt}`)}},[s,i.sessionId,z]),co=g.useCallback(()=>E(null),[]),Lm=N==="files"&&P&&s?{title:"Edited Files",onBack:co,content:h.jsx(Ble,{api:s,scope:Xl,sessionId:i.sessionId,onShareFile:lo,onOpenInTab:pd,onPreviewMarkdown:Mi})}:N==="cron"?{title:`定时任务${De.length?` (${De.length})`:""}`,onBack:co,content:h.jsx("div",{className:"p-3",children:h.jsx(wse,{jobs:De})})}:N==="persona"&&A&&s&&i.ownerPersonaId?{title:`Persona · ${R??""}`,onBack:co,content:h.jsx(eue,{personaId:i.ownerPersonaId,open:!0,onClose:co,api:s,embedded:!0,...m?{viewerRole:m}:{}},i.ownerPersonaId)}:null,gd=He==="full"?h.jsx(fse,{session:i,meta:la,...$&&O.binding?{liveGitBranch:((xr=O.workspace)==null?void 0:xr.actualBranch)??null}:o!==void 0?{liveGitBranch:o}:{},...a!==void 0?{liveWorktreeRoot:a}:{},...A?{personaName:R}:{},...A?{onOpenPersona:()=>E("persona")}:{},...P?{onOpenFiles:()=>E("files")}:{},cronActiveCount:De.length,onCronClick:()=>E("cron"),onForceStop:()=>be(!0),...ox(i.tool)&&e.reloadFromCloud?{onReloadFromCloud:e.reloadFromCloud,reloadFromCloudDisabled:ni}:{},...m?{viewerRole:m}:{},...b!=null&&b.toolSessionIdLabel?{toolSessionIdLabel:b.toolSessionIdLabel}:{},drill:Lm,...nn?{onCollapse:nn}:{},...fn?{title:fn.title,leadingEntries:fn.leadingEntries}:{}}):null;return h.jsxs(h.Fragment,{children:[$&&bn?Do.createPortal(h.jsx(kue,{controller:O,disabled:la.streamInProgress}),bn):null,At&&gd?Do.createPortal(gd,At):null,h.jsx(Mue,{headerMeta:la,workspaceInput:$?h.jsx(Sue,{controller:O,disabled:la.streamInProgress}):void 0,workspaceInputDisabled:$&&O.busy,connState:e.connState,...a!==void 0?{liveWorktreeRoot:a}:{},...d?{onOpenConfig:d}:{},variant:He,...v||$?{hideHeader:!0}:{},..._?{flatProcess:_}:{},...He==="quickask"?{ephemeral:i.ephemeral!==!1,onPromote:()=>void(x==null?void 0:x(i.sessionId))}:{},lines:oe,pendingPermissions:je,procAlive:Ce,rewindableUserMessageIds:ue,onPermissionRespond:Yl,onPermissionInterrupt:yt,onRewind:S.rewind?W:void 0,...f&&S.fork?{onFork:f}:{},...n&&S.fork?{onQuickAsk:n}:p&&S.fork?{onQuickAsk:p}:{},topSlot:fd,codexHistory:e.codexHistory,realtimeQuestionAnswers:oa,onSubmitQuestion:aa,onCancelQuestion:Gl,liveQuestionToolUseIds:hs,api:s,cwd:i.cwd,...i.tool?{tool:i.tool}:{},...l?{cloudVolume:l}:{},sessionKey:i.sessionId,onSend:e.sendText,queued:e.queued,onDequeue:e.dequeue,awaitingUser:je.length>0||Object.values(B).some(Z=>!Z.submittedAnswers),onAbort:yt,...c?{onNewSession:c}:{},onClearSession:fs,...w?{configSlot:w}:{},chatRootRef:Se,chatBodyRef:it,drawers:Gt,xtermSlot:I==="tui"&&Ce&&S.tui?h.jsx(Ole,{sessionId:i.sessionId,client:F},i.sessionId):null,fileSharingScope:Xl,...s?{onShareFile:lo}:{},...s?{onOpenInTab:pd}:{},...s?{onPreviewMarkdown:Mi}:{},...s?{onOpenFilePath:jm}:{},dispatchOrigin:L}),s?h.jsx(oue,{open:jt,onOpenChange:$t,relPath:Wn,loadMarkdown:md,onShare:Wn?()=>void lo(Wn,"md-rendered"):void 0}):null,C?h.jsx("div",{"data-testid":"share-toast",role:"status","aria-live":"polite",className:C.kind==="ok"?"fixed left-1/2 top-4 z-50 -translate-x-1/2 rounded-md border border-emerald-500/40 bg-emerald-500/10 px-3 py-2 text-[12px] text-emerald-700 shadow-md dark:text-emerald-300":"fixed left-1/2 top-4 z-50 -translate-x-1/2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-[12px] text-destructive shadow-md",children:C.text}):null]})}function Aue({onConfirm:e,onCancel:t}){return h.jsx("div",{role:"dialog","aria-modal":"true","data-testid":"force-stop-confirm",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40",onClick:t,children:h.jsxs("div",{className:"max-w-sm w-[92%] rounded-lg border border-red-400/40 bg-bg-0 p-4 shadow-xl",onClick:n=>n.stopPropagation(),children:[h.jsxs("div",{className:"flex items-start gap-2 mb-3",children:[h.jsx(Ff,{className:"w-5 h-5 text-red-500 shrink-0 mt-0.5"}),h.jsx("div",{className:"text-[14px] text-text-100",children:"强制停止会话进程?会丢失 initialize / 预热缓存,下一次发送需要重新 spawn。"})]}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{type:"button",onClick:t,className:"h-8 px-3 rounded-md text-[12px] text-text-300 hover:bg-text-100/5 cursor-pointer",children:"取消"}),h.jsx("button",{type:"button","data-testid":"force-stop-confirm-ok",onClick:e,className:"h-8 px-3 rounded-md bg-red-500 text-white text-[12px] font-medium hover:bg-red-600 cursor-pointer",children:"强制停止"})]})]})})}function jue(e){return e.split("/").pop()||e}function Lue({state:e,api:t,onSwitchTab:n,onCloseQuickAsk:r,onCloseMd:i,loadMarkdown:s,quickAskSession:o,onPromoteQuickAsk:a}){if(!GP(e))return null;const l=[];e.quickAsk&&l.push({id:"quick-ask",label:"问一下",title:"问一下",icon:h.jsx(cx,{className:"w-3.5 h-3.5"})});for(const c of e.mds)l.push({id:{kind:"md",relPath:c},label:jue(c),title:c,icon:h.jsx(Ci,{className:"w-3.5 h-3.5"})});return h.jsxs("div",{className:"flex flex-col h-full bg-bg-50/60 border-l border-border-strong",children:[h.jsx(Nu,{delayDuration:200,skipDelayDuration:100,children:h.jsx("div",{className:["flex items-stretch h-9 border-b border-text-100/10 shrink-0 overflow-x-auto","[scrollbar-width:none] [-ms-overflow-style:none]","[&::-webkit-scrollbar]:hidden"].join(" "),role:"tablist",children:l.map(c=>{const u=uY(e.active,c.id),d=c.id==="quick-ask"?"quick-ask":`md:${c.id.relPath}`;return h.jsxs(ed,{children:[h.jsx(td,{asChild:!0,children:h.jsxs("div",{role:"tab","aria-selected":u,"data-tab-title":c.title,onClick:()=>n(c.id),className:["group relative flex items-center gap-2 px-3 h-full cursor-pointer select-none","text-[12px] max-w-[180px] shrink-0 transition-colors duration-100",u?"text-text-100":"text-text-400 hover:text-text-100 hover:bg-text-100/[0.04]"].join(" "),children:[c.icon,h.jsx("span",{className:"truncate",children:c.label}),h.jsx("button",{type:"button","aria-label":`关闭 ${c.label}`,className:["ml-1 rounded p-0.5 shrink-0 transition-opacity","hover:bg-text-100/10",u?"opacity-70 hover:opacity-100":"opacity-0 group-hover:opacity-70"].join(" "),onClick:f=>{f.stopPropagation(),c.id==="quick-ask"?r():i(c.id.relPath)},children:h.jsx(Qr,{className:"w-3 h-3"})}),u?h.jsx("span",{"aria-hidden":"true",className:"absolute left-2 right-2 -bottom-px h-[2px] rounded-full bg-accent"}):null]})}),h.jsx(Hl,{side:"bottom",align:"start",className:"max-w-sm break-all",children:c.title})]},d)})})}),h.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[e.quickAsk&&o?h.jsx("div",{className:"absolute inset-0",style:{display:e.active==="quick-ask"?"block":"none"},children:h.jsx(Rue,{session:o,api:t,...a?{onPromoteQuickAsk:a}:{}})}):null,e.mds.map(c=>{const u=e.active!==null&&e.active!=="quick-ask"&&e.active.relPath===c;return h.jsx("div",{className:"absolute inset-0",style:{display:u?"block":"none"},children:h.jsx(ij,{relPath:c,loadMarkdown:s,showTitleBar:!1})},`md-body:${c}`)})]})]})}function Due(e){const t=e instanceof Error?e.message:String(e);return t.length>200?`${t.slice(0,200)}…`:t}function Oue({state:e,extras:t}){const{api:n,session:r}=t,i=Ni(),[s,o]=g.useState(rY()),[a,l]=g.useState(null),c=r.ownerPersonaId!==ST,u=g.useRef(s);u.current=s;const d=g.useRef(!1),f=g.useCallback(async E=>{const j=u.current.quickAsk;l(null);let P;try{P=await YG(n,r,E)}catch(D){Oe("quick-ask","fork failed",D),d.current||l(Due(D));return}if(!P){d.current||l("这条会话还没准备好(没有可派生的对话记录),稍后再试");return}if(d.current){n.sessionDelete(P.sessionId).catch(()=>{});return}nh(j)&&n.sessionDelete(j.sessionId).catch(()=>{}),o(D=>iY(D,{sessionId:P.sessionId}))},[n,r]),p=g.useCallback(async E=>{const j=u.current.quickAsk,P=(j==null?void 0:j.sessionId)===E;try{await XG(n,{sessionId:E,stillEphemeral:P&&nh(j)})&&o(R=>aY(R))}catch(D){Oe("quick-ask","promote failed",D)}},[n]),m=g.useCallback(E=>{o(j=>sY(j,E))},[]),x=g.useCallback(E=>{o(j=>cY(j,E))},[]),w=g.useCallback(()=>{const E=u.current.quickAsk;nh(E)&&n.sessionDelete(E.sessionId).catch(()=>{}),o(j=>oY(j))},[n]),v=g.useCallback(E=>{o(j=>lY(j,E))},[]);g.useEffect(()=>()=>{d.current=!0;const E=u.current.quickAsk;nh(E)&&n.sessionDelete(E.sessionId).catch(()=>{})},[]);const _=ts("sessions")??[],b=s.quickAsk?_.find(E=>E.sessionId===s.quickAsk.sessionId)??{sessionId:s.quickAsk.sessionId,cwd:r.cwd,tool:r.tool}:null,S=g.useCallback(async E=>{const j=await F_(n,i,r.sessionId,E,60),P=await fetch(j);if(!P.ok)throw new Error(`fetch ${P.status} ${P.statusText}`);return P.text()},[n,i,r.sessionId]),C=h.jsx(wj,{state:e,extras:t,onQuickAskInternal:f,onPreviewMdInternal:m}),{initialSize:k,setSize:N}=nY("chat-panel-right-slot-width",480);return h.jsxs(B_,{orientation:"horizontal",className:"flex-1 flex min-w-0 min-h-0",children:[h.jsx(Yf,{id:"chat",minSize:"400px",children:h.jsxs("div",{className:"relative flex flex-col min-w-0 min-h-0 h-full",children:[C,a?h.jsxs("div",{"data-testid":"quick-ask-error",className:"absolute bottom-24 left-1/2 z-10 -translate-x-1/2 max-w-[90%] rounded-md border border-border bg-bg-200 px-3 py-2 text-[12px] text-text-300 shadow-lg",children:[h.jsxs("span",{className:"mr-2",children:["问一下没能打开:",a]}),h.jsx("button",{type:"button","aria-label":"关闭提示",onClick:()=>l(null),className:"text-text-400 hover:text-text-200 cursor-pointer",children:"✕"})]}):null]})}),GP(s)?h.jsxs(h.Fragment,{children:[h.jsx(FP,{className:"w-1 bg-text-100/10 hover:bg-text-100/25 transition-colors cursor-col-resize"}),h.jsx(Yf,{id:"right-slot",defaultSize:`${k}px`,minSize:"360px",maxSize:"800px",onResize:E=>N(E.inPixels),children:h.jsx(Lue,{state:s,api:n,onSwitchTab:x,onCloseQuickAsk:w,onCloseMd:v,loadMarkdown:S,quickAskSession:b,...c?{onPromoteQuickAsk:p}:{}})})]}):null]})}function Bue({extras:e}){const t=KP(e.session.sessionId,e.focused);return h.jsx(Oue,{state:t,extras:e})}function $ue(e,t,n){const r=e?t.find(s=>s.id===e):void 0;if(r!=null&&r.efforts&&r.efforts.length>0)return{options:r.efforts,defaultValue:r.defaultEffort??""};const i=n.find(s=>s.name==="effort");return{options:(i==null?void 0:i.options)??[],defaultValue:typeof(i==null?void 0:i.default)=="string"?i.default:""}}function zue(e,t,n){var l;if(!t)return((l=(e??[]).find(c=>c.id===""))==null?void 0:l.label)??"未指定";const r=t.toLowerCase(),i=[["opus","Opus"],["fable","Fable"],["sonnet","Sonnet"],["haiku","Haiku"]];for(const[c,u]of i){if(!r.includes(c))continue;const d=r.match(new RegExp(`${c}-(\\d+)(?:-(\\d+))?`));return d?d[2]?`${u} ${d[1]}.${d[2]}`:`${u} ${d[1]}`:u}const s=e??[],o=s.find(c=>c.id===t);if(o)return o.label;const a=s.find(c=>c.id&&t.toLowerCase().includes(c.id.toLowerCase()));return a?a.label:t}function Fue(e,t){var m,x,w,v;const{models:n,modes:r,configSchema:i}=t,s=e.resolvedModel??e.model,o=$ue(s,n,i),a=o.options,l=a.some(_=>_.value===e.effort)?e.effort:o.defaultValue,c=e.effort===""&&e.resolvedEffort?((m=a.find(_=>_.value===e.resolvedEffort))==null?void 0:m.label)??e.resolvedEffort:((x=a.find(_=>_.value===l))==null?void 0:x.label)??null,u=((w=i.find(_=>_.name==="permissionMode"))==null?void 0:w.default)??"",d=r.some(_=>_.id===e.permissionMode)?e.permissionMode:u,p=d===u?null:((v=r.find(_=>_.id===d))==null?void 0:v.label)??null;return{modelLabel:zue(n,s),effortOptions:a,effortValue:l,effortLabel:c,modeValue:d,modeLabel:p,modeTone:p===null?null:d==="bypassPermissions"?"danger":"info"}}function Sj(e){let t;return e.map(n=>{const r=n.group&&n.group!==t?n.group:null;return n.group&&(t=n.group),{...n,groupHeading:r}})}function Hue(e){return e.map(t=>({value:t.id,label:t.label,...t.description?{description:t.description}:{},...t.group?{group:t.group}:{}}))}function Uue({testid:e,list:t,options:n,current:r,onSelect:i}){if(t.loading)return h.jsx(Wr,{disabled:!0,"data-testid":`${e}-loading`,className:"text-[12px] text-text-400",children:"正在读取最新模型…"});if(t.error)return h.jsxs(h.Fragment,{children:[h.jsx("div",{"data-testid":`${e}-error`,className:"px-2 py-1.5 text-[11px] text-warning",children:t.error}),h.jsx(Wr,{"data-testid":`${e}-retry`,className:"text-[12px]",onSelect:o=>{o.preventDefault(),t.load()},children:"重试"})]});const s=n??Hue(t.models);return s.length===0?h.jsx(Wr,{disabled:!0,"data-testid":`${e}-empty`,className:"text-[12px] text-text-400",children:"没有可选模型"}):h.jsx(h.Fragment,{children:Sj(s).map((o,a)=>{const l=o.value===r;return h.jsxs(Qe.Fragment,{children:[o.groupHeading?h.jsxs(h.Fragment,{children:[a>0?h.jsx(hm,{}):null,h.jsx(I_,{"data-testid":`${e}-group`,children:o.groupHeading})]}):null,h.jsxs(Wr,{"data-testid":`${e}-option-${o.value||"default"}`,onSelect:()=>i(o.value),className:"items-start gap-2",children:[h.jsxs("span",{className:"min-w-0 flex-1",children:[h.jsx("span",{className:re("block text-[12px]",l?"font-medium text-text-100":"text-text-300"),children:o.label}),o.description?h.jsx("span",{className:"mt-0.5 block text-[11px] text-text-400",children:o.description}):null]}),l?h.jsx(Zo,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-accent"}):null]})]},o.value||"default")})})}function Wue(e,t={}){return{models:e,loading:!1,error:null,load:()=>{},...t}}const que=e=>e instanceof Error?e.message:String(e);function Vue(e,t){const[n,r]=g.useState({key:e,loading:!1,error:null,data:t}),i=g.useRef(0),s=g.useCallback((a,l)=>{const c=++i.current;r(u=>({key:e,loading:!0,error:null,data:u.key===e?u.data:t})),a().then(u=>{i.current===c&&(l==null||l(u),r({key:e,loading:!1,error:null,data:u}))},u=>{i.current===c&&r(d=>({key:e,loading:!1,error:que(u),data:d.key===e?d.data:t}))})},[e]);return{...n.key===e?n:{loading:!1,error:null,data:t},run:s}}const Kue=[];function Gue(e){const t=Ni(),n=g.useMemo(()=>new Xp(t),[t]),r=as(),{capabilities:i}=Im(e),s=Vue(e??"",null),{run:o}=s,a=g.useCallback(()=>{e&&o(()=>n.capabilitiesGet(e,{refresh:!0}),l=>{l&&r.setData(`capabilities/${e}`,()=>l)})},[n,r,e,o]);return{models:(i==null?void 0:i.models)??Kue,loading:s.loading,error:s.error,load:a}}function Yue({models:e,modelList:t,modes:n=[],configSchema:r=[],model:i,resolvedModel:s,resolvedEffort:o,effort:a,permissionMode:l,onPatch:c}){var w;const u=t??Wue(e??[]),d=u.models,f=Fue({model:i,resolvedModel:s,resolvedEffort:o,effort:a,permissionMode:l},{models:d,modes:n,configSchema:r}),p=s??i,m=d.map(v=>{const _=v.id===""&&s?`${v.description?`${v.description};`:""}当前:${s}`:v.description;return{value:v.id,label:v.label,..._?{description:_}:{},...v.group?{group:v.group}:{}}}),x=n.map(v=>({value:v.id,label:v.label,...v.description?{description:v.description}:{}}));return h.jsxs(uP,{children:[h.jsx(dP,{asChild:!0,children:h.jsxs("button",{type:"button","data-testid":"session-config-chip",title:"Model / reasoning effort / permission mode",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full text-[11px] text-text-400 transition-colors outline-none cursor-pointer hover:bg-text-100/5 hover:text-text-200 data-[state=open]:bg-text-100/5",children:[h.jsx("span",{className:"truncate max-w-[120px]","data-testid":"session-config-chip-model",children:p||f.modelLabel}),f.effortLabel?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"text-text-500",children:"·"}),h.jsx("span",{className:"truncate max-w-[80px]","data-testid":"session-config-chip-effort",children:f.effortLabel})]}):null,f.modeLabel?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"text-text-500",children:"·"}),h.jsx("span",{"data-testid":"session-config-chip-mode","data-tone":f.modeTone,className:re("font-semibold",f.modeTone==="danger"?"text-red-400":"text-blue-400"),children:f.modeLabel})]}):null]})}),h.jsxs(k_,{side:"top",align:"end",className:"w-[230px]","data-testid":"session-config-menu",children:[h.jsx(Xue,{list:u,current:i,currentLabel:f.modelLabel,options:m,onSelect:v=>c({model:v})}),h.jsx(NE,{testid:"session-config-effort",label:"Reasoning effort",current:f.effortValue,currentLabel:f.effortLabel??"—",options:f.effortOptions,onSelect:v=>c({effort:v})}),x.length>0?h.jsx(NE,{testid:"session-config-mode",label:"Permission mode",current:f.modeValue,currentLabel:((w=n.find(v=>v.id===f.modeValue))==null?void 0:w.label)??"—",currentTone:f.modeTone,options:x,onSelect:v=>c({permissionMode:v})}):null]})]})}function kj({label:e,currentLabel:t,currentTone:n}){return h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"flex-1 text-text-200",children:e}),h.jsx("span",{className:re("truncate max-w-[100px]",n==="danger"?"text-red-400 font-semibold":n==="info"?"text-blue-400 font-semibold":"text-text-400"),children:t}),h.jsx(Fn,{className:"w-3.5 h-3.5 shrink-0 text-text-500"})]})}function Xue({list:e,current:t,currentLabel:n,options:r,onSelect:i}){const[s,o]=g.useState(!1),a=l=>{l&&!s&&e.load(),o(l)};return h.jsxs(hP,{open:s,onOpenChange:a,children:[h.jsx(C_,{"data-testid":"session-config-model",className:"gap-2 text-[12px]",children:h.jsx(kj,{label:"Model",currentLabel:n})}),h.jsx(E_,{className:"w-[220px] max-h-[320px] overflow-y-auto",children:h.jsx(Uue,{testid:"session-config-model",list:e,options:r,current:t,onSelect:i})})]})}function NE({testid:e,label:t,current:n,currentLabel:r,currentTone:i,options:s,onSelect:o}){const a=s.length===0;return h.jsxs(hP,{children:[h.jsx(C_,{"data-testid":e,disabled:a,className:"gap-2 text-[12px]",children:h.jsx(kj,{label:t,currentLabel:r,currentTone:i??null})}),h.jsx(E_,{className:"w-[220px] max-h-[320px] overflow-y-auto",children:Sj(s).map((l,c)=>{const u=l.value===n;return h.jsxs(Qe.Fragment,{children:[l.groupHeading?h.jsxs(h.Fragment,{children:[c>0?h.jsx(hm,{}):null,h.jsx(I_,{"data-testid":`${e}-group`,children:l.groupHeading})]}):null,h.jsxs(Wr,{"data-testid":`${e}-option-${l.value||"default"}`,onSelect:()=>o(l.value),className:"items-start gap-2",children:[h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:re("block text-[12px]",u?"text-text-100 font-medium":"text-text-300"),children:l.label}),l.description?h.jsx("span",{className:"block text-[11px] text-text-400 mt-0.5",children:l.description}):null]}),u?h.jsx(Zo,{className:"w-3.5 h-3.5 shrink-0 text-accent mt-0.5"}):null]})]},l.value||"default")})})]})}function Zue(e,t,n=0){const[r,i]=g.useState(null),[s,o]=g.useState(!1),a=g.useCallback(async()=>{if(!t){i(null);return}o(!0);try{const l=await e.getGitBranch(t);i(l.branch??null)}catch{i(null)}finally{o(!1)}},[e,t]);return g.useEffect(()=>{a()},[a,n]),{branch:r,loading:s,refresh:()=>void a()}}function Que(e,t,n=0){const[r,i]=g.useState(null),[s,o]=g.useState(!1),a=g.useCallback(async()=>{if(!t){i(null);return}o(!0);try{const l=await e.getGitRoot(t);i(l.gitRoot??null)}catch{i(null)}finally{o(!1)}},[e,t]);return g.useEffect(()=>{a()},[a,n]),{worktreeRoot:r,loading:s,refresh:()=>void a()}}const Jue=5e3;function ede(e,t,n=0){const[r,i]=g.useState(null);return g.useEffect(()=>{if(!t){i(null);return}let s=!1;const o=async()=>{try{const l=await e.cloudVolumeGet();s||i(l.volume??null)}catch{s||i(null)}},a=n>0?setTimeout(()=>void o(),Jue):null;return a||o(),()=>{s=!0,a&&clearTimeout(a)}},[e,t,n]),{volume:r}}const tde=90;function nde(e){return e.sizeBytes>0?Math.min(100,Math.max(0,Math.round(e.usedBytes/e.sizeBytes*100))):0}function TE(e){const t=e/1073741824;return t>=.1?`${t.toFixed(1)} GB`:`${Math.max(1,Math.round(e/1024**2))} MB`}function rde({volume:e}){if(!e)return null;const t=nde(e),n=t>=tde?"warn":"ok",r=new Date(e.measuredAt).toLocaleString(),i=n==="ok"?"上一次任务结束时量的。":"盘快满了:在会话里说「清理一下云盘」,persona 会分析工作区里哪些能删、列给你确认后清掉。";return h.jsxs("span",{"data-testid":"chat-header-cloud-volume","data-tone":n,title:`云盘已用 ${TE(e.usedBytes)} / ${TE(e.sizeBytes)}(${r})。${i}`,className:re("ml-1.5 inline-flex items-center gap-1.5 px-1.5 py-0.5 rounded text-[11px] tabular-nums",n==="ok"&&"bg-text-100/10 text-text-400",n==="warn"&&"bg-warning-dim text-warning"),children:[h.jsx("span",{className:"relative inline-block w-8 h-1 rounded-full bg-current/20 overflow-hidden","aria-hidden":!0,children:h.jsx("span",{className:"absolute inset-y-0 left-0 rounded-full bg-current",style:{width:`${t}%`}})}),"云盘 ",t,"%"]})}function ide({api:e,session:t,focused:n,totalPanes:r,onFocus:i,onClose:s,onNewSession:o,onOpenConfig:a,onFork:l,onQuickAsk:c,className:u,viewerRole:d="owner",hideHeader:f}){const{capabilities:p}=Im(t.tool),m=Gue(t.tool),[x,w]=g.useState(0),[v,_]=g.useState(n);Qe.useEffect(()=>{n&&_(!0)},[n]);const b=ox(t.tool),S=b?void 0:t.cwd,{branch:C}=Zue(e,S,x),{worktreeRoot:k}=Que(e,S,x),{volume:N}=ede(e,b,x),E=r>1,j=P=>{e.sessionUpdate(t.sessionId,P).catch(D=>{console.error("[session-config] session:update failed",t.sessionId,D)})};return h.jsxs("div",{className:`group/pane relative flex-1 ${u??"flex"} flex-row min-w-0 min-h-0 overflow-hidden ${E?`rounded-md border transition-colors ${n?"border-accent ring-1 ring-accent":"border-border"}`:""}`,onMouseDown:i,"data-testid":`session-pane-${t.sessionId}`,children:[h.jsx(B_,{orientation:"horizontal",className:"flex-1 flex min-w-0 min-h-0",children:h.jsx(Yf,{id:"chat",minSize:"400px",children:h.jsx("div",{className:"flex flex-col min-w-0 min-h-0 h-full",children:(n||v)&&h.jsx(sde,{api:e,session:t,focused:n,liveGitBranch:C,liveWorktreeRoot:k,...b&&N?{cloudVolume:h.jsx(rde,{volume:N})}:{},onNewSession:o,onTurnEnd:()=>w(P=>P+1),onOpenConfig:a,onFork:l,onQuickAsk:c,viewerRole:d,hideHeader:f,configSlot:p?h.jsx(Yue,{modelList:m,modes:p.permissionModes,configSchema:p.configSchema,model:t.model??"",...t.resolvedModel?{resolvedModel:t.resolvedModel}:{},...t.resolvedEffort?{resolvedEffort:t.resolvedEffort}:{},effort:t.effort??"",permissionMode:t.permissionMode??"",onPatch:j}):null})})})}),E&&h.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),s()},className:"absolute top-1.5 right-1.5 z-10 p-1 rounded-md bg-bg-100/80 backdrop-blur-sm border border-border opacity-0 group-hover/pane:opacity-100 transition-opacity text-text-400 hover:text-text-100 hover:bg-bg-200","aria-label":"close pane","data-testid":`session-pane-close-${t.sessionId}`,children:h.jsx(Qr,{className:"w-3.5 h-3.5"})})]})}function sde({api:e,session:t,focused:n,liveGitBranch:r,liveWorktreeRoot:i,cloudVolume:s,onNewSession:o,onTurnEnd:a,onOpenConfig:l,onFork:c,onQuickAsk:u,viewerRole:d,configSlot:f,hideHeader:p}){return h.jsx(Bue,{extras:{session:t,api:e,focused:n,...r!==void 0?{liveGitBranch:r}:{},...i!==void 0?{liveWorktreeRoot:i}:{},...s!==void 0?{cloudVolume:s}:{},onNewSession:o,onTurnEnd:a,onOpenConfig:l,...c?{onFork:m=>{c(m)}}:{},...u?{onQuickAsk:m=>{u(m)}}:{},...d?{viewerRole:d}:{},...f?{configSlot:f}:{},...p?{hideHeader:p}:{}}})}function ode({personas:e,sessions:t,api:n,selfPrincipalId:r,selectedPersonaId:i,selectedSessionId:s,selectedSession:o,onSelectPersona:a,onSelectSession:l,onCreateSession:c,onDeleteSession:u,onEditSession:d,onCloseSession:f}){return h.jsxs("div",{className:"flex h-screen min-h-0 bg-bg-50","data-testid":"guest-share-page",children:[h.jsx("aside",{className:"w-[280px] shrink-0 overflow-y-auto border-r border-border bg-bg-50",children:h.jsx(AK,{personas:e,sessions:t,activePersonaId:i,activeSessionId:s,onSelectPersona:a,onSelectSession:l,onCreateSession:c,onDeleteSession:u,onEditSession:d,showCopyResume:!1,treatSessionsAsRoots:!0,...r?{ownerPrincipalId:r}:{},isPersonaExpanded:()=>!0})}),h.jsx("main",{className:"flex-1 min-w-0 min-h-0 flex",children:o?h.jsx(ide,{api:n,session:o,focused:!0,totalPanes:1,onFocus:()=>{},onClose:f,onNewSession:()=>{},onOpenConfig:()=>{},viewerRole:"guest"}):h.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-xs text-text-400","data-testid":"guest-share-empty",children:"选择左侧 persona 开始对话"})})]})}function ade(){const e=Ni(),t=g.useMemo(()=>new Xp(e),[e]),n=Lz(e),{sessions:r,refresh:i}=Dz(n),{personas:s}=XT(),o=Hz(),a=g.useMemo(()=>{const S=window.location.pathname.match(/^\/s\/([^/]+)/);return S?decodeURIComponent(S[1]):null},[]),l=g.useMemo(()=>r.filter(S=>!S.ephemeral&&S.larkChatId==null),[r]),c=g.useMemo(()=>a?s.filter(S=>S.personaId===a):s,[s,a]),[u,d]=g.useState(null),[f,p]=g.useState(null),[m,x]=g.useState(null);g.useEffect(()=>{let S=!1;return e.request("whoami",{}).then(C=>{S||d(C.capability.id)}).catch(()=>{}),()=>{S=!0}},[e]),g.useEffect(()=>{a&&p(a)},[a]);const w=g.useCallback(async(S,C)=>{const k=await t.sessionCreate({ownerPersonaId:S,...C.trim()?{label:C.trim()}:{}});await i(),p(S),x(k.sessionId)},[t,i]),v=g.useCallback(async S=>{await t.sessionDelete(S),await i(),x(C=>C===S?null:C)},[t,i]),_=g.useCallback(async(S,C)=>{await t.sessionUpdate(S,{label:C.label}),await i()},[t,i]),b=g.useMemo(()=>l.find(S=>S.sessionId===m)??null,[l,m]);return h.jsx(Yy.Provider,{value:o,children:h.jsx(ode,{personas:c,sessions:l,api:t,selfPrincipalId:u,selectedPersonaId:f,selectedSessionId:m,selectedSession:b,onSelectPersona:p,onSelectSession:x,onCreateSession:(S,C)=>void w(S,C),onDeleteSession:S=>void v(S),onEditSession:(S,C)=>void _(S,C),onCloseSession:()=>x(null)})})}const PE="https://app.ttcadvisory.com";function lde({onAuthed:e}){const[t,n]=g.useState(!1),[r,i]=g.useState(null),s=g.useRef(null);g.useEffect(()=>()=>{s.current&&window.removeEventListener("message",s.current)},[]);const o=g.useCallback(()=>{s.current&&(window.removeEventListener("message",s.current),s.current=null),n(!0),i(null);const a=window.location.origin,l=`${PE}/auth/authorize?callback_url=${encodeURIComponent(a)}&auto=1`,c=async d=>{if(d.origin!==PE)return;const f=d.data;if((f==null?void 0:f.type)==="AUTH_CANCEL"){u(),n(!1);return}if(!((f==null?void 0:f.type)!=="AUTH_SUCCESS"||!f.token)){u();try{const p=await fetch(`${window.location.origin}/share/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ttcToken:f.token})});if(!p.ok){const x=await p.json().catch(()=>({}));throw new Error(x.code??`exchange failed (${p.status})`)}const m=await p.json();if(!m.visitorToken)throw new Error("no visitorToken in response");e(m.visitorToken)}catch(p){i(p instanceof Error?p.message:String(p)),n(!1)}}},u=()=>{window.removeEventListener("message",c),s.current=null};s.current=d=>void c(d),window.addEventListener("message",s.current),window.open(l,"ttc-login","width=480,height=640")},[e]);return h.jsx("div",{className:"flex min-h-screen items-center justify-center bg-bg-50 p-6 font-sans text-text-100","data-testid":"guest-login",children:h.jsxs("div",{className:"flex w-full max-w-xs flex-col gap-3 rounded-lg border border-border bg-bg-100 px-5 py-6",children:[h.jsx("h1",{className:"text-base font-semibold",children:"登录后进入分享"}),h.jsx("p",{className:"text-[11px] leading-snug text-text-400",children:"使用飞书账号登录,即可在浏览器里与分享给你的 persona 交互,无需安装。"}),r?h.jsxs("p",{className:"text-[11px] leading-snug text-error","data-testid":"guest-login-error",children:["登录失败:",r]}):null,h.jsx("button",{type:"button",disabled:t,onClick:()=>o(),"data-testid":"guest-login-button",className:"w-full rounded border border-border bg-bg-50 px-2 py-1.5 text-xs text-text-200 transition-colors hover:bg-text-100/5 hover:text-text-100 disabled:opacity-50",children:t?"请在弹窗中完成授权…":"飞书登录"})]})})}const C1="clawd-visitor:token";function cde(e,t){const r=`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}`;return t!=null&&t.devPath?`${r}${t.devPath}`:r}function ude(){return{async getUrl(e){const t=localStorage.getItem(C1);if(!t)throw new Error("NO_VISITOR_TOKEN");const n=cde(window.location,{});return await FT(e).upsert({id:"guest",name:"访客",mode:"remote",url:n,token:t}),{url:n}}}}function dde(e){const t=n=>{document.documentElement.classList.toggle("dark",n==="dark")};return t(e.theme.mode),e.onThemeChange(n=>t(n.mode))}function hde(){const e=Ni(),t=g.useMemo(()=>jz(e),[e]);return h.jsx(mz,{cache:t.cache,children:h.jsx(xz,{children:h.jsx(ade,{})})})}function fde({host:e}){const[t]=g.useState(()=>localStorage.getItem(C1)),[n,r]=g.useState(!1),[i,s]=g.useState(null);return g.useEffect(()=>dde(e),[e]),g.useEffect(()=>{if(!t)return;let o=!1;return ude().getUrl(e).then(()=>{o||r(!0)}).catch(a=>{o||s(a instanceof Error?a.message:String(a))}),()=>{o=!0}},[e,t]),t?h.jsx(Vw,{host:e,children:h.jsx(CS,{children:i?h.jsxs("div",{className:"flex min-h-screen items-center justify-center bg-bg-50 p-6 text-center text-xs text-error","data-testid":"guest-share-connect-error",children:["连接失败:",i]}):n?h.jsx(hz,{host:e,children:h.jsx(hde,{})}):h.jsx("div",{className:"flex min-h-screen items-center justify-center bg-bg-50 p-6 text-xs text-text-400",children:"正在连接…"})})}):h.jsx(Vw,{host:e,children:h.jsx(CS,{children:h.jsx(lde,{onAuthed:o=>{localStorage.setItem(C1,o),window.location.reload()}})})})}function pde({filePath:e,oldString:t,newString:n,content:r}){const i=g.useMemo(()=>r!=null?r.split(/\r?\n/).map(s=>({type:"add",text:s})):mde(t??"",n??""),[t,n,r]);return h.jsxs("div",{"data-testid":"inline-diff",className:"min-w-0 max-w-full rounded-lg border border-bg-300/60 bg-bg-50 overflow-hidden text-[12px] font-mono",children:[h.jsx("div",{className:"flex min-w-0 items-center gap-2 px-3 py-1.5 border-b border-bg-300/40 bg-bg-100/30",children:h.jsx("span",{className:"min-w-0 text-text-400 truncate",title:e,children:e})}),h.jsx("div",{className:"max-h-[320px] max-w-full overflow-auto",children:i.map((s,o)=>h.jsxs("div",{"data-testid":`diff-line-${s.type}`,className:re("flex min-w-max gap-2 px-3 py-0.5 whitespace-pre",s.type==="add"?"bg-success/10 text-success":s.type==="remove"?"bg-error/10 text-error":"text-text-300"),children:[h.jsx("span",{className:"w-3 shrink-0 select-none opacity-60",children:s.type==="add"?"+":s.type==="remove"?"-":" "}),h.jsx("span",{className:"flex-1",children:s.text||" "})]},o))})]})}function mde(e,t){const n=e.split(/\r?\n/),r=t.split(/\r?\n/),i=n.length,s=r.length,o=Array.from({length:i+1},()=>new Array(s+1).fill(0));for(let u=i-1;u>=0;u--)for(let d=s-1;d>=0;d--)o[u][d]=n[u]===r[d]?o[u+1][d+1]+1:Math.max(o[u+1][d],o[u][d+1]);const a=[];let l=0,c=0;for(;l<i&&c<s;)n[l]===r[c]?(a.push({type:"equal",text:n[l]}),l++,c++):o[l+1][c]>=o[l][c+1]?(a.push({type:"remove",text:n[l]}),l++):(a.push({type:"add",text:r[c]}),c++);for(;l<i;)a.push({type:"remove",text:n[l++]});for(;c<s;)a.push({type:"add",text:r[c++]});return a}function gde({items:e}){return e.length===0?null:h.jsxs("div",{"data-testid":"todo-checklist",className:"rounded-lg border border-bg-300/60 bg-bg-50 px-3 py-2 text-[13px]",children:[h.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-text-400/70 mb-1.5",children:"Todos"}),h.jsx("ul",{className:"flex flex-col gap-1",children:e.map((t,n)=>{const r=t.status==="in_progress"&&t.activeForm||t.content;return h.jsxs("li",{"data-testid":`todo-item-${t.status}`,className:"flex items-start gap-2",children:[h.jsx(vde,{status:t.status}),h.jsx("span",{className:re("flex-1 leading-snug",t.status==="completed"?"text-text-400 line-through":t.status==="in_progress"?"text-text-100 font-medium":"text-text-200"),children:r})]},n)})})]})}function vde({status:e}){return e==="completed"?h.jsx(Xy,{className:"w-3.5 h-3.5 text-success mt-0.5 shrink-0"}):e==="in_progress"?h.jsx(Tn,{className:"w-3.5 h-3.5 text-warning mt-0.5 shrink-0 animate-spin"}):h.jsx(_7,{className:"w-3.5 h-3.5 text-text-400 mt-0.5 shrink-0"})}function xde(e){const t=e??{};return Array.isArray(t.todos)?t.todos.map(n=>{if(!n||typeof n!="object")return null;const r=n,i=typeof r.content=="string"?r.content:"",s=r.status==="pending"||r.status==="in_progress"||r.status==="completed"?r.status:"pending",o=typeof r.activeForm=="string"?r.activeForm:void 0;return{content:i,status:s,activeForm:o}}).filter(n=>n!==null):[]}function yde({description:e,prompt:t,subagentType:n}){return h.jsxs("div",{"data-testid":"task-checklist",className:"rounded-lg border border-bg-300/60 bg-bg-50 px-3 py-2 text-[13px]",children:[h.jsxs("div",{className:"flex items-center gap-2 text-text-200 font-medium",children:[h.jsx(Zp,{className:"w-3.5 h-3.5 text-accent shrink-0"}),h.jsx("span",{className:"truncate",children:e||"subagent task"}),n?h.jsx("span",{className:"shrink-0 px-1.5 py-0.5 rounded-md text-[10px] font-mono bg-accent/10 text-accent",children:n}):null]}),t?h.jsx("div",{className:"mt-1 text-[12px] text-text-400 leading-snug line-clamp-3",children:t}):null]})}function _de(e){const t=e??{};return{description:typeof t.description=="string"?t.description:"",prompt:typeof t.prompt=="string"?t.prompt:void 0,subagentType:typeof t.subagent_type=="string"?t.subagent_type:void 0}}const bde={render:({input:e})=>Qe.createElement(gde,{items:xde(e)})},wde={render:({input:e})=>{const{description:t,prompt:n,subagentType:r}=_de(e);return Qe.createElement(yde,{description:t,prompt:n,subagentType:r})}},RE={render:({input:e,output:t,error:n,pending:r,fileScope:i,onShareFile:s,onOpenInTab:o,onPreviewMarkdown:a})=>{const l=kde(e),c=l?Qe.createElement(pde,{filePath:l.filePath,oldString:l.oldString,newString:l.newString,content:l.content}):void 0;return Qe.createElement(vM,{tool:Sde(e),input:e,output:t,error:n,pending:r,expandedBody:c,...i?{fileScope:i}:{},...s?{onShareFile:s}:{},...o?{onOpenInTab:o}:{},...a?{onPreviewMarkdown:a}:{}})}};function Sde(e){const t=e??{};return"content"in t&&t.content!==void 0?"Write":("old_string"in t&&t.old_string!==void 0,"Edit")}function kde(e){const t=e??{},n=typeof t.file_path=="string"?t.file_path:null;if(!n)return null;const r=typeof t.old_string=="string"?t.old_string:void 0,i=typeof t.new_string=="string"?t.new_string:void 0,s=typeof t.content=="string"?t.content:void 0;return r==null&&i==null&&s==null?null:{filePath:n,oldString:r,newString:i,content:s}}for(const e of["claude",r9])$a.register(e,"TodoWrite",bde),$a.register(e,"Task",wde),$a.register(e,"Edit",RE),$a.register(e,"Write",RE);const Cj=document.getElementById("root");if(!Cj)throw new Error("guest-main: #root not found");const Cde=sO({});S0.createRoot(Cj).render(h.jsx(Qe.StrictMode,{children:h.jsx(fde,{host:Cde})}));
622
+ For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return g.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Bce="DialogDescriptionWarning",$ce=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${YA(Bce).contentName}}.`;return g.useEffect(()=>{var s;const i=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&i&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},zce=DA,Fce=$A,XA=zA,ZA=FA,QA=UA,JA=qA,Hce=KA;const ej=zce,Uce=Fce,tj=g.forwardRef(({className:e,...t},n)=>h.jsx(XA,{ref:n,className:re("fixed inset-0 z-50 bg-black/50 backdrop-blur-sm",e),...t}));tj.displayName=XA.displayName;const Eb=g.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(Uce,{children:[h.jsx(tj,{}),h.jsxs(ZA,{ref:r,className:re("fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2","gap-4 rounded-lg border border-border bg-elevated p-6 shadow-lg",e),...n,children:[t,h.jsxs(Hce,{className:"absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-accent",children:[h.jsx(Qr,{className:"h-4 w-4"}),h.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Eb.displayName=ZA.displayName;const nj=({className:e,...t})=>h.jsx("div",{className:re("flex flex-col space-y-1.5 text-left",e),...t});nj.displayName="DialogHeader";const Ib=g.forwardRef(({className:e,...t},n)=>h.jsx(QA,{ref:n,className:re("text-lg font-semibold leading-none text-text-100",e),...t}));Ib.displayName=QA.displayName;const rj=g.forwardRef(({className:e,...t},n)=>h.jsx(JA,{ref:n,className:re("text-sm text-text-300",e),...t}));rj.displayName=JA.displayName;function Wce({persona:e,open:t,onClose:n,onDelete:r,embedded:i,onLoadPersonality:s,onSavePersonality:o,onLoadPersonalityLocal:a,onSavePersonalityLocal:l,hasPersonalityLocal:c=!1,onDirtyChange:u,initialPersonality:d,onShareCapability:f,readOnly:p=!1,larkBot:m}){const[x,w]=g.useState(!1),[v,_]=g.useState(!1),b=x||v,S=Qe.useRef(u);g.useEffect(()=>{S.current=u}),g.useEffect(()=>{var k;(k=S.current)==null||k.call(S,b)},[b]);const C=()=>{b&&!window.confirm("修改未保存,确定关闭?")||n()};return t?h.jsxs(h.Fragment,{children:[!i&&h.jsx("div",{className:"absolute inset-0 z-30 bg-black/30",onClick:C,"aria-hidden":"true"}),h.jsxs("aside",{className:i?"flex h-full w-full flex-col bg-bg-0":"absolute right-0 top-0 z-40 flex h-full w-[420px] flex-col bg-bg-0 border-l border-border shadow-xl","data-testid":"persona-settings-drawer",children:[h.jsxs("header",{className:"flex items-center justify-between border-b border-border px-4 py-3 shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[h.jsx(IF,{className:"h-4 w-4 text-text-300"}),h.jsx("span",{className:"text-[13px] font-medium text-text-100 truncate",children:"Persona 设置"})]}),h.jsx("button",{type:"button",onClick:C,"aria-label":"关闭",className:"rounded-sm p-1.5 text-text-400 hover:bg-bg-200 hover:text-text-100",children:h.jsx(Qr,{className:"h-4 w-4"})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto p-6 flex flex-col gap-4",children:[h.jsxs("header",{className:"flex items-start justify-between gap-3",children:[h.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("h2",{className:"text-lg font-semibold text-text-100 truncate",children:e.label}),e.public?h.jsxs("span",{className:"inline-flex items-center gap-1 rounded-sm bg-bg-200 px-1.5 py-0.5 text-[10px] text-text-200",children:[h.jsx(V7,{className:"h-3 w-3"})," 公开"]}):h.jsxs("span",{className:"inline-flex items-center gap-1 rounded-sm bg-error-dim px-1.5 py-0.5 text-[10px] text-error",children:[h.jsx(W7,{className:"h-3 w-3"})," 已关闭"]})]}),h.jsx("span",{className:"font-mono text-[11px] text-text-400 truncate","data-testid":"persona-id-subtitle",children:e.personaId})]}),h.jsxs("div",{className:"flex items-center gap-1",children:[f?h.jsxs("button",{type:"button",onClick:f,"aria-label":"分享给他人",title:"分享给他人",className:"inline-flex items-center gap-1 rounded-sm px-2 py-1.5 text-xs text-text-200 hover:bg-bg-200 hover:text-text-100",children:[h.jsx(Qy,{className:"h-3.5 w-3.5"}),"分享"]}):null,r?h.jsx("button",{type:"button",onClick:r,"aria-label":"删除 persona",className:"rounded-sm p-1.5 text-text-400 hover:bg-bg-200 hover:text-error",children:h.jsx(Jy,{className:"h-4 w-4"})}):null]})]}),h.jsx("hr",{className:"border-border"}),m?h.jsxs(h.Fragment,{children:[h.jsx(Kce,{...m}),h.jsx("hr",{className:"border-border"})]}):null,s?h.jsxs(h.Fragment,{children:[h.jsx(CE,{onLoad:s,...o&&!e.personalityManaged?{onSave:o}:{},onDirtyChange:w,initialPersonality:d,readOnly:p||!!e.personalityManaged,title:e.personalityManaged?"内置人格":"人格 (Personality)",hint:e.personalityManaged?p?"这个 persona 自带的人格,随 clawd 版本更新。":"这个 persona 自带的人格,随 clawd 版本更新——在这里改不会保留,要加自己的规则请写下面的「你的补充」。":void 0,testIdPrefix:"persona-personality"}),(e.personalityManaged||c)&&a?h.jsx(CE,{onLoad:a,...l?{onSave:l}:{},onDirtyChange:_,readOnly:p,title:p?"补充设定":"你的补充",hint:p?"这个 persona 的补充设定,由它的主人维护。与内置人格叠加生效。":"写入 <persona-dir>/.clawd/personality.local.md,不会被更新覆盖。与内置人格叠加生效,冲突时以你写的为准;对 owner 和访客会话都生效,要区分对象请在正文里写明。只对新启动的会话生效。",placeholder:"例:回答一律先给结论,再展开。",testIdPrefix:"persona-personality-local"}):null,h.jsx("hr",{className:"border-border"})]}):null,h.jsx(Gce,{settings:e.sandboxSettings??null}),h.jsx("hr",{className:"border-border"}),h.jsx(Yce,{skills:e.skills??[]}),h.jsx("hr",{className:"border-border"}),h.jsx(Xce,{plugins:e.plugins??[]})]})]})]}):null}function kE({qrUrl:e,busy:t,onCancel:n,title:r="扫码关联飞书 Bot",hint:i="用手机飞书扫码,按页面提示创建应用。确认后自动完成关联。"}){const[s,o]=g.useState(null);return g.useEffect(()=>{let a=!1;return ud.toDataURL(e,{width:240,margin:1}).then(l=>{a||o(l)}).catch(()=>{a||o(null)}),()=>{a=!0}},[e]),h.jsx(ej,{open:!0,onOpenChange:a=>a||n==null?void 0:n(),children:h.jsxs(Eb,{className:"max-w-xs","data-testid":"lark-bot-qr-dialog",onInteractOutside:a=>a.preventDefault(),onEscapeKeyDown:a=>a.preventDefault(),children:[h.jsx(nj,{children:h.jsx(Ib,{children:r})}),h.jsxs("div",{className:"flex flex-col items-center gap-2",children:[s?h.jsx("img",{src:s,alt:"飞书扫码创建应用二维码",className:"h-60 w-60 rounded bg-white p-2","data-testid":"lark-bot-qr-img"}):h.jsx("div",{className:"flex h-60 w-60 items-center justify-center text-[12px] text-text-400",children:"二维码生成中…"}),h.jsx("span",{className:"text-center text-[12px] text-text-300",children:i}),n?h.jsx("button",{type:"button",disabled:t,onClick:n,className:"rounded border border-border px-3 py-1.5 text-[12px] text-text-300 hover:bg-bg-200 disabled:opacity-50","data-testid":"lark-bot-provision-cancel",children:"取消"}):null]})]})})}const qce={expired:"二维码已过期,请重新扫码。",cancelled:"已取消。",access_denied:"你在飞书上取消了本次授权。",lark_protocol_error:"飞书返回了未预期的响应,请重试。",cloud_unreachable:"云端暂时不可达,请稍后重试。",internal_error:"关联失败。若飞书中已创建应用,可在开发者后台删除后重试,或改用手动绑定填入其凭证。"},Vce=new Set(["expired","access_denied","lark_protocol_error","cloud_unreachable","internal_error"]);function Kce({status:e,onProvision:t,onCancelProvision:n,onBindManual:r,onUnbind:i,onUpgrade:s,runtime:o="local"}){const[a,l]=g.useState(!1),[c,u]=g.useState(null),[d,f]=g.useState(""),[p,m]=g.useState(""),[x,w]=g.useState(null),v=N=>{N&&(l(!0),u(null),N().catch(E=>u(E instanceof Error?E.message:String(E))).finally(()=>l(!1)))},_=()=>{w(null),v(t)},b=!a&&!!d&&!!p,S=()=>{!b||!r||v(()=>r({appId:d,appSecret:p}))},C=Ju(S),k=h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx(Zp,{className:"h-3.5 w-3.5 text-text-400","aria-hidden":!0}),h.jsx("span",{className:"text-[13px] font-medium text-text-100",children:"飞书 Bot"})]});return e?h.jsxs("section",{className:"flex flex-col gap-1.5","data-testid":"lark-bot-section",children:[k,e.state==="unbound"||e.state==="provisioning"?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"text-[11px] text-text-400",children:["关联一个飞书 bot 后,这个 persona 就是它:拉进群后群成员 @ 它提问、或直接私聊它,",o==="cloud"?"云 Persona 在云端处理消息,回复自动发回去。":"推理跑在你本机,回复自动发回去。"]}),t?h.jsx("button",{type:"button",disabled:a||e.state==="provisioning",onClick:_,className:"self-start rounded border border-border bg-bg-200 px-3 py-1.5 text-[12px] font-medium text-text-100 hover:bg-bg-300 disabled:opacity-50","data-testid":"lark-bot-provision",children:e.state==="provisioning"?"等待扫码…":"扫码关联飞书 Bot"}):null,e.state==="unbound"&&e.errorReason&&!x?h.jsxs("div",{className:"flex flex-col gap-1.5 rounded border border-error bg-error-dim px-2 py-1.5","data-testid":"lark-bot-provision-error",children:[h.jsx("span",{className:"text-[11px] text-error",children:qce[e.errorReason]}),h.jsxs("div",{className:"flex gap-1.5",children:[Vce.has(e.errorReason)&&t?h.jsx("button",{type:"button",disabled:a,onClick:_,className:"rounded border border-border px-2 py-1 text-[11px] text-text-100 hover:bg-bg-200 disabled:opacity-50","data-testid":"lark-bot-provision-retry",children:"重新扫码"}):null,h.jsx("button",{type:"button",onClick:()=>w(e.errorReason??null),className:"rounded border border-border px-2 py-1 text-[11px] text-text-300 hover:bg-bg-200","data-testid":"lark-bot-provision-error-dismiss",children:"知道了"})]})]}):null,e.state==="provisioning"&&e.qrUrl?h.jsx(kE,{qrUrl:e.qrUrl,busy:a,onCancel:n?()=>v(n):void 0}):null,r&&e.state==="unbound"?h.jsxs("details",{"data-testid":"lark-bot-manual-details",children:[h.jsx("summary",{className:"cursor-pointer text-[11px] text-text-400 hover:text-text-300",children:"已有飞书应用?手动填入凭证"}),h.jsxs("div",{className:"mt-1.5 flex flex-col gap-1.5","data-testid":"lark-bot-manual-form",children:[h.jsx("span",{className:"text-[11px] text-text-400",children:"先在飞书开放平台(open.feishu.cn)创建企业自建应用并启用机器人能力,再填入凭证:"}),h.jsx("input",{value:d,onChange:N=>f(N.target.value),...C,placeholder:"App ID(cli_ 开头)",className:"rounded border border-border bg-bg-100 px-2 py-1 text-[12px] text-text-200","data-testid":"lark-bot-manual-appid"}),h.jsx("input",{value:p,onChange:N=>m(N.target.value),...C,type:"password",placeholder:"App Secret",className:"rounded border border-border bg-bg-100 px-2 py-1 text-[12px] text-text-200","data-testid":"lark-bot-manual-secret"}),h.jsx("button",{type:"button",disabled:!b,onClick:S,className:"self-start rounded border border-border px-3 py-1.5 text-[12px] text-text-100 hover:bg-bg-200 disabled:opacity-50","data-testid":"lark-bot-manual-submit",children:a?"绑定中…":"绑定"})]})]}):null]}):null,e.state==="bound"||e.state==="broken"?h.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.state==="bound"&&e.needsUpgrade?h.jsxs("div",{className:"flex flex-col gap-1.5 rounded border border-warning/30 bg-warning-dim px-2 py-1.5","data-testid":"lark-bot-upgrade-notice",children:[h.jsx("span",{className:"text-[11px] text-warning",children:"这个 bot 的权限配置有更新,扫码重新授权后生效。在此之前,新增能力对它不起作用。"}),s?h.jsx("button",{type:"button",disabled:a,onClick:()=>v(s),className:"self-start rounded border border-warning/30 bg-warning/10 px-2 py-1 text-[11px] text-warning hover:bg-warning/20 disabled:opacity-50","data-testid":"lark-bot-upgrade",children:"更新授权"}):null]}):null,e.state==="bound"&&e.upgradeQrUrl?h.jsx(kE,{qrUrl:e.upgradeQrUrl,busy:a,onCancel:n?()=>v(n):void 0,title:"扫码更新授权",hint:"用手机飞书扫码,确认页会列出将要添加的权限。期间 bot 照常服务,不会中断。"}):null,e.state==="broken"?h.jsxs("div",{className:"rounded border border-error bg-error-dim px-2 py-1.5 text-[11px] text-error","data-testid":"lark-bot-broken",children:["Bot 凭证失效:",e.brokenReason??"未知原因","。请解绑后重新填入有效凭证绑定。"]}):null,h.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-text-200",children:[h.jsx("span",{className:"font-medium text-text-100",children:e.botName??"未命名 bot"}),e.appId?h.jsx("span",{className:"text-[11px] text-text-400",children:e.appId}):null]}),h.jsx("span",{className:"text-[11px] text-text-400",children:"把 bot 拉进任意飞书群,群成员 @ 它即可提问。"}),e.groups.length>0?h.jsx("ul",{className:"flex flex-col gap-0.5","data-testid":"lark-bot-groups",children:e.groups.map(N=>h.jsxs("li",{className:"text-[11px] text-text-300 truncate",children:["· ",N.chatName??N.chatId]},N.chatId))}):h.jsx("span",{className:"text-[11px] text-text-400","data-testid":"lark-bot-groups-empty",children:"还没有服务中的群。"}),i?h.jsx("button",{type:"button",disabled:a,onClick:()=>v(i),className:"self-start rounded border border-border px-3 py-1.5 text-[12px] text-error hover:bg-error-dim disabled:opacity-50","data-testid":"lark-bot-unbind",children:"解绑"}):null]}):null,c?h.jsx("div",{className:"rounded border border-error bg-error-dim px-2 py-1.5 text-[11px] text-error","data-testid":"lark-bot-error",children:c}):null]}):h.jsxs("section",{className:"flex flex-col gap-1.5","data-testid":"lark-bot-section",children:[k,h.jsx("span",{className:"text-[11px] text-text-400",children:"状态加载中…"})]})}function Gce({settings:e}){var t,n,r,i,s,o,a,l,c,u,d,f,p;return h.jsxs("section",{className:"flex flex-col gap-2","data-testid":"persona-sandbox-setting-section",children:[h.jsxs("header",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-[13px] font-medium text-text-100",children:"Sandbox Setting"}),h.jsx("span",{className:"text-[11px] text-text-400",children:"约束此 persona 的沙箱权限(只读,需通过文件修改)。"})]}),e==null?h.jsx("span",{className:"text-[12px] text-text-300","data-testid":"persona-sandbox-setting-empty",children:"暂无 sandbox 配置"}):h.jsxs("div",{className:"flex flex-col gap-1.5 rounded-md border border-border bg-bg-100 px-3 py-2",children:[h.jsx(vh,{label:"权限默认模式",value:((t=e.permissions)==null?void 0:t.defaultMode)??"—"}),h.jsx(vh,{label:"沙箱启用",value:w0((n=e.sandbox)==null?void 0:n.enabled)}),h.jsx(vh,{label:"沙箱内自动放行 Bash",value:w0((r=e.sandbox)==null?void 0:r.autoAllowBashIfSandboxed)}),h.jsx(vh,{label:"允许非沙箱命令",value:w0((i=e.sandbox)==null?void 0:i.allowUnsandboxedCommands)}),h.jsxs("div",{className:"mt-1 flex flex-col gap-1.5 border-t border-border pt-1.5",children:[h.jsx(vc,{label:"沙箱外命令",paths:(s=e.sandbox)==null?void 0:s.excludedCommands}),h.jsx(vc,{label:"允许读取",paths:(a=(o=e.sandbox)==null?void 0:o.filesystem)==null?void 0:a.allowRead}),h.jsx(vc,{label:"拒绝读取",paths:(c=(l=e.sandbox)==null?void 0:l.filesystem)==null?void 0:c.denyRead}),h.jsx(vc,{label:"允许写入",paths:(d=(u=e.sandbox)==null?void 0:u.filesystem)==null?void 0:d.allowWrite}),h.jsx(vc,{label:"拒绝写入",paths:(p=(f=e.sandbox)==null?void 0:f.filesystem)==null?void 0:p.denyWrite})]})]})]})}function w0(e){return e===!0?"是":e===!1?"否":"—"}function vh({label:e,value:t}){return h.jsxs("div",{className:"flex items-center justify-between gap-3 text-[12px]",children:[h.jsx("span",{className:"text-text-300",children:e}),h.jsx("span",{className:"font-mono text-text-100",children:t})]})}function vc({label:e,paths:t}){const n=!t||t.length===0;return h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsx("span",{className:"text-[11px] text-text-300",children:e}),n?h.jsx("span",{className:"text-[11px] text-text-400",children:"—"}):h.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((r,i)=>h.jsx("span",{className:"rounded-sm border border-border bg-bg-0 px-1.5 py-0.5 font-mono text-[11px] text-text-200",children:r},`${e}-${i}-${r}`))})]})}function Yce({skills:e}){return h.jsxs("section",{className:"flex flex-col gap-2","data-testid":"persona-skills-section",children:[h.jsxs("header",{className:"flex flex-col gap-0.5",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-[13px] font-medium text-text-100",children:"Persona Skills"}),h.jsx("span",{className:"rounded-sm border border-border px-1.5 py-0.5 text-[10px] text-text-300",children:e.length})]}),h.jsxs("span",{className:"text-[11px] text-text-400",children:["此 persona 私有 skills(来自"," ",h.jsx("code",{className:"font-mono",children:"<persona-dir>/.claude/skills/"}),")。"]})]}),e.length===0?h.jsx("span",{className:"text-[12px] text-text-300","data-testid":"persona-skills-empty",children:"暂无 skills"}):h.jsx("ul",{className:"flex flex-col divide-y divide-border rounded-md border border-border bg-bg-100",children:e.map(t=>h.jsxs("li",{className:"flex flex-col gap-0.5 px-3 py-2","data-testid":"persona-skill-row",children:[h.jsx("span",{className:"font-mono text-[13px] text-text-100",children:t.name}),t.description?h.jsx("span",{className:"text-[12px] text-text-300",children:t.description}):h.jsx("span",{className:"text-[11px] text-text-400 italic",children:"无描述"})]},t.name))})]})}function Xce({plugins:e}){return h.jsxs("section",{className:"flex flex-col gap-2","data-testid":"persona-plugins-section",children:[h.jsxs("header",{className:"flex flex-col gap-0.5",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-[13px] font-medium text-text-100",children:"Enabled Plugins"}),h.jsx("span",{className:"rounded-sm border border-border px-1.5 py-0.5 text-[10px] text-text-300",children:e.length})]}),h.jsxs("span",{className:"text-[11px] text-text-400",children:["此 persona 已启用的插件(来自"," ",h.jsx("code",{className:"font-mono",children:"<persona-dir>/.claude/settings.json"})," ","的 ",h.jsx("code",{className:"font-mono",children:"enabledPlugins"}),")。"]})]}),e.length===0?h.jsx("span",{className:"text-[12px] text-text-300","data-testid":"persona-plugins-empty",children:"暂无启用插件"}):h.jsx("ul",{className:"flex flex-col divide-y divide-border rounded-md border border-border bg-bg-100",children:e.map(t=>h.jsx("li",{className:"flex flex-col gap-0.5 px-3 py-2","data-testid":"persona-plugin-row",children:h.jsx("span",{className:"font-mono text-[13px] text-text-100",children:t.id})},t.id))})]})}function CE({onLoad:e,onSave:t,onDirtyChange:n,initialPersonality:r,readOnly:i=!1,title:s,hint:o,placeholder:a,testIdPrefix:l}){const c=r!==void 0,[u,d]=g.useState(c),[f,p]=g.useState(c?r:""),[m,x]=g.useState(c?r:""),[w,v]=g.useState(null),[_,b]=g.useState(!1),[S,C]=g.useState(null),k=Qe.useRef(e),N=Qe.useRef(t),E=Qe.useRef(n);Qe.useEffect(()=>{k.current=e,N.current=t,E.current=n});const j=Qe.useCallback(()=>{d(!1),v(null),k.current().then(M=>{p(M),x(M),d(!0)}).catch(M=>{v(M instanceof Error?M.message:String(M))})},[]);Qe.useEffect(()=>{c||j()},[c,j]);const P=!i&&u&&m!==f;Qe.useEffect(()=>{i||E.current(P)},[P,i]);const D=()=>{N.current&&(b(!0),C(null),N.current(m).then(()=>{p(m),b(!1)}).catch(M=>{C(M instanceof Error?M.message:String(M)),b(!1)}))},R=()=>{x(f),C(null)},A=Ju(()=>{!P||_||D()},()=>{!P||_||R()});return h.jsxs("section",{className:"flex flex-col gap-2","data-testid":`${l}-section`,children:[h.jsx("span",{className:"text-[12px] font-medium text-text-200",children:s}),w?h.jsxs("div",{"data-testid":`${l}-load-error`,className:"rounded-md border border-error bg-error-dim px-3 py-2 text-[12px] text-error flex items-center justify-between gap-2",children:[h.jsxs("span",{children:["加载失败:",w]}),h.jsx("button",{type:"button",onClick:j,className:"rounded-sm border border-error px-2 py-0.5 text-[11px] hover:bg-error/10",children:"重试"})]}):null,S?h.jsxs("div",{"data-testid":`${l}-save-error`,className:"rounded-md border border-error bg-error-dim px-3 py-2 text-[12px] text-error",children:["保存失败:",S]}):null,h.jsx("textarea",{"data-testid":`${l}-textarea`,value:m,onChange:M=>x(M.target.value),...A,readOnly:i,disabled:!i&&(!u||_),placeholder:u?a??"":"加载中…",rows:8,className:"min-h-[8rem] max-h-[18rem] resize-y rounded-md border border-border bg-bg-100 px-2 py-1.5 font-mono text-[11px] text-text-100 disabled:opacity-60"}),o?h.jsx("p",{className:"text-[10px] text-text-400",children:o}):i?null:h.jsx("p",{className:"text-[10px] text-text-400",children:"写入人格文件。修改只对新启动的会话生效。"}),u&&P?h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{type:"button",onClick:R,disabled:_,className:"rounded-sm border border-border px-2 py-1 text-[12px] text-text-200 hover:bg-bg-200 disabled:opacity-60",children:"放弃"}),h.jsx("button",{type:"button",onClick:D,disabled:_,"data-testid":`${l}-save-btn`,className:"rounded-sm bg-accent-dim px-2 py-1 text-[12px] text-text-100 hover:opacity-90 disabled:opacity-60",children:_?"保存中…":"保存"})]}):null]})}const Zce={state:"unbound",groups:[]};function Qce(e,t,n="local"){const[r,i]=g.useState(null),s=d=>`${n==="cloud"?"cloud:":""}larkBot:${d}`;g.useEffect(()=>{if(!e)return;let d=!1,f=0,p=!1;i(null);const m=async()=>{const _=++f;p=!0;try{const b=await e.request(s("status"),{personaId:t});if(d||_!==f)return;i(S=>n==="cloud"&&(S!=null&&S.upgradeQrUrl)&&b.state==="bound"&&b.needsUpgrade!==!1?{...b,upgradeQrUrl:S.upgradeQrUrl}:b.state==="unbound"&&!b.errorReason&&(S==null?void 0:S.state)==="unbound"&&S.errorReason?{...b,errorReason:S.errorReason}:b)}catch{!d&&_===f&&i(b=>b??Zce)}finally{_===f&&(p=!1)}};m();const x=e.on("larkBot:state",_=>{const b=_;if(b.personaId!==t)return;const{personaId:S,...C}=b;++f,p=!1,i(C)}),w=e.on("daemon:connected",()=>{m()}),v=n==="cloud"?setInterval(()=>{p||m()},5e3):null;return()=>{d=!0,v&&clearInterval(v),x(),w()}},[e,t,n]);const o=g.useCallback(async()=>{e&&await e.request(s("provision"),{personaId:t})},[e,t,n]),a=g.useCallback(async()=>{e&&await e.request(s("provisionCancel"),{personaId:t})},[e,t,n]),l=g.useCallback(async d=>{e&&await e.request(s("bindManual"),{personaId:t,...d})},[e,t,n]),c=g.useCallback(async()=>{e&&await e.request(s("upgrade"),{personaId:t})},[e,t,n]),u=g.useCallback(async()=>{e&&await e.request(s("unbind"),{personaId:t})},[e,t,n]);return{status:r,provision:o,cancelProvision:a,bindManual:l,unbind:u,upgrade:c}}function Jce(e,t="owner"){var N;const{persona:n}=ZT(e),r=Oz(e),i=Bz(),s=$z(),{httpBaseUrl:o}=Yp(),a=Ni(),l=Qce(t==="guest"?null:a,e),{capabilities:c}=Im((n==null?void 0:n.tool)??"claude"),u=g.useMemo(()=>!(n!=null&&n.public)||!o||/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[?::1\]?)([:/]|$)/i.test(o)?null:`${o}/s/${e}`,[n==null?void 0:n.public,o,e]),d=g.useCallback((E,j)=>{i(e,j).catch(P=>{Oe("persona",`${E} failed`,P)})},[i,e]),f=g.useCallback(E=>d("togglePublic",{public:E}),[d]),p=g.useCallback(async E=>{await i(e,{codexSandbox:{network:E}}),await r.refresh()},[i,e,r]),m=g.useCallback(E=>d("changeTool",{tool:E}),[d]),x=g.useCallback(E=>d("changeModel",{model:E}),[d]),w=g.useCallback(E=>d("changeEffort",{effort:E}),[d]),v=g.useCallback(E=>d("toggleFastMode",{serviceTier:E?Bf.fast:Bf.standard}),[d]),_=g.useCallback(()=>!n||!confirm(`删除 persona "${n.label}"?`)?!1:(s(e).catch(E=>{Oe("persona","delete failed",E)}),!0),[n,s,e]),b=g.useCallback(async()=>r.loaded?r.personality:(await r.refresh()).personality,[r]),S=g.useCallback(async E=>{await i(e,{personality:E}),await r.refresh()},[i,e,r]),C=g.useCallback(async()=>r.loaded?r.personalityLocal:(await r.refresh()).personalityLocal,[r]),k=g.useCallback(async E=>{await i(e,{personalityLocal:E}),await r.refresh()},[i,e,r]);return{persona:n,detail:r,configSchema:(c==null?void 0:c.configSchema)??[],larkBot:l,guestShareUrl:u,changeTool:m,changeModel:x,changeEffort:w,toggleFastMode:v,togglePublic:f,guestNetwork:((N=r.codexSandbox)==null?void 0:N.network)??!1,toggleGuestNetwork:p,remove:_,loadPersonality:b,savePersonality:S,loadPersonalityLocal:C,savePersonalityLocal:k}}function eue({personaId:e,open:t,onClose:n,api:r,embedded:i,onDirtyChange:s,onShareCapability:o,viewerRole:a="owner"}){const l=Jce(e,a),{persona:c,detail:u}=l,d=g.useCallback(()=>{l.remove()&&n()},[l,n]);if(!c)return null;const f=a==="guest";return h.jsx(Wce,{embedded:i,persona:{...c,skills:u.skills,plugins:u.plugins,sandboxSettings:u.sandboxSettings,personalityManaged:u.personalityManaged},open:t,onClose:n,onLoadPersonality:l.loadPersonality,onLoadPersonalityLocal:l.loadPersonalityLocal,hasPersonalityLocal:u.personalityLocal!=="",onDirtyChange:s,readOnly:f,...f?{}:{onTogglePublic:l.togglePublic,guestShareUrl:l.guestShareUrl,onChangeTool:l.changeTool,onChangeModel:l.changeModel,onChangeEffort:l.changeEffort,configSchema:l.configSchema,onDelete:d,onSavePersonality:l.savePersonality,onSavePersonalityLocal:l.savePersonalityLocal,larkBot:{status:l.larkBot.status,onProvision:l.larkBot.provision,onCancelProvision:l.larkBot.cancelProvision,onBindManual:l.larkBot.bindManual,onUnbind:l.larkBot.unbind,onUpgrade:l.larkBot.upgrade},...o?{onShareCapability:o}:{}}})}const tue={resolve:()=>{}},nue=g.createContext(tue);function rue(){return g.useContext(nue)}const iue={...Qs,h1:({node:e,...t})=>h.jsx("h1",{...t,className:"mt-4 mb-3 text-[18px] font-semibold leading-tight text-text-100"}),h2:({node:e,...t})=>h.jsx("h2",{...t,className:"mt-4 mb-2 text-[16px] font-semibold leading-tight text-text-100"}),h3:({node:e,...t})=>h.jsx("h3",{...t,className:"mt-3 mb-2 text-[14px] font-semibold leading-tight text-text-100"}),h4:({node:e,...t})=>h.jsx("h4",{...t,className:"mt-3 mb-1 text-[13px] font-semibold text-text-100"}),h5:({node:e,...t})=>h.jsx("h5",{...t,className:"mt-2 mb-1 text-[12px] font-semibold text-text-100"}),h6:({node:e,...t})=>h.jsx("h6",{...t,className:"mt-2 mb-1 text-[12px] font-semibold text-text-300"}),p:({node:e,...t})=>h.jsx("p",{...t,className:"my-2 leading-relaxed"}),ul:({node:e,...t})=>h.jsx("ul",{...t,className:"my-2 list-disc space-y-1 pl-5"}),ol:({node:e,...t})=>h.jsx("ol",{...t,className:"my-2 list-decimal space-y-1 pl-5"}),li:({node:e,...t})=>h.jsx("li",{...t,className:"leading-relaxed"}),blockquote:({node:e,...t})=>h.jsx("blockquote",{...t,className:"my-2 border-l-2 border-border pl-3 italic text-text-300"}),code:({node:e,className:t,children:n,...r})=>t?h.jsx("code",{...r,className:`${t} font-mono text-[12px]`,children:n}):h.jsx("code",{...r,className:"rounded bg-bg-50 px-1 py-0.5 font-mono text-[12px] text-text-100",children:n}),pre:({node:e,...t})=>h.jsx("pre",{...t,className:"my-2 overflow-auto rounded border border-border bg-bg-0 p-3 text-[12px] font-mono text-text-100"}),hr:({node:e,...t})=>h.jsx("hr",{...t,className:"my-3 border-border"}),table:({node:e,...t})=>h.jsx("table",{...t,className:"my-2 w-full border-collapse text-[12px]"}),thead:({node:e,...t})=>h.jsx("thead",{...t,className:"bg-bg-50"}),th:({node:e,...t})=>h.jsx("th",{...t,className:"border border-border px-2 py-1 text-left font-semibold"}),td:({node:e,...t})=>h.jsx("td",{...t,className:"border border-border px-2 py-1"}),strong:({node:e,...t})=>h.jsx("strong",{...t,className:"font-semibold text-text-100"}),em:({node:e,...t})=>h.jsx("em",{...t,className:"italic"})};function sue(e){const t=e.split("/");return t[t.length-1]||e}function ij({relPath:e,loadMarkdown:t,headerRight:n,showTitleBar:r=!1}){const[i,s]=g.useState(null),[o,a]=g.useState(null),[l,c]=g.useState(!1);return g.useEffect(()=>{if(!e)return;let u=!1;return c(!0),a(null),s(null),(async()=>{try{const d=await t(e);if(u)return;s(d)}catch(d){if(u)return;a(d.message||String(d))}finally{u||c(!1)}})(),()=>{u=!0}},[e,t]),h.jsxs("div",{className:"flex flex-col h-full",children:[r&&e?h.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[h.jsx("div",{"data-testid":"md-preview-title",className:"truncate text-[13px] font-medium text-text-100",title:e,children:sue(e)}),h.jsx("div",{className:"flex items-center gap-1",children:n})]}):null,h.jsx("div",{className:"flex-1 overflow-auto px-4 py-3 text-[13px] text-text-100",children:l?h.jsx("div",{"data-testid":"md-preview-loading",className:"text-text-400",children:"Loading…"}):o?h.jsx("div",{"data-testid":"md-preview-error",className:"text-destructive whitespace-pre-wrap",children:o}):i!==null?h.jsx("div",{"data-testid":"md-preview-content",className:"max-w-none",children:h.jsx(xl,{remarkPlugins:[yl],components:iue,children:i})}):null})]})}function oue({open:e,onOpenChange:t,relPath:n,loadMarkdown:r,onShare:i}){return e?h.jsx("div",{"data-testid":"md-preview-drawer",className:`${ab} z-50 flex w-1/2 max-w-[900px] flex-col border-l border-border bg-elevated shadow-2xl`,children:h.jsx(ij,{relPath:n,loadMarkdown:r,showTitleBar:!0,headerRight:h.jsxs(h.Fragment,{children:[i?h.jsx("button",{type:"button","data-testid":"md-preview-share","aria-label":"Share rendered preview link",onClick:i,className:"inline-flex h-6 w-6 items-center justify-center rounded text-text-400 hover:bg-bg-50 hover:text-text-200",children:h.jsx(eF,{className:"h-4 w-4"})}):null,h.jsx("button",{type:"button","aria-label":"Close preview",onClick:()=>t(!1),className:"inline-flex h-6 w-6 items-center justify-center rounded text-text-400 hover:bg-bg-50 hover:text-text-200",children:h.jsx(Qr,{className:"h-4 w-4"})})]})})}):null}const EE=4;function aue({children:e,onHeightChange:t}){const n=g.useRef(null),[r,i]=g.useState(0);return g.useEffect(()=>{const s=n.current;if(!s)return;const o=()=>i(s.offsetHeight>0?s.offsetHeight+EE*2:0);if(o(),typeof ResizeObserver>"u")return;const a=new ResizeObserver(o);return a.observe(s),()=>a.disconnect()},[]),g.useEffect(()=>{t==null||t(r)},[r,t]),h.jsx("div",{"data-testid":"chat-floating-dock","data-height":r,className:"relative z-20 h-0 shrink-0",children:h.jsx("div",{ref:n,className:"absolute left-4 right-4 flex flex-col items-end gap-1",style:{bottom:EE},children:e})})}function lue(e,t,n,r,i,s){const[o,a]=g.useState(null),[l,c]=g.useState(i??null),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(null),w=g.useRef({api:e,sessionId:t,enabled:n,epoch:0,read:null,again:!1,mutating:!1}),v=g.useRef({api:e,sessionId:t,enabled:n});v.current={api:e,sessionId:t,enabled:n};const _=g.useRef(t),b=g.useRef(async()=>{}),S=N=>{if(N.workspace!==void 0&&a(N.workspace),N.binding!==void 0)c(N.binding);else if(N.workspace){const{workspaceId:E,repoId:j,owner:P,name:D,sourceBranch:R,defaultBranch:A}=N.workspace;c({workspaceId:E,repoId:j,owner:P,name:D,sourceBranch:R,defaultBranch:A})}},C=g.useCallback(async()=>{const N=w.current;if(!n||N.sessionId!==t||N.api!==e)return;if(N.mutating){N.again=!0;return}if(N.read)return N.again=!0,N.read;const E=N.epoch;d(!0);const j=(async()=>{try{const P=await e.cloudWorkspace({sessionId:t,action:"status"});w.current===N&&N.epoch===E&&v.current.sessionId===t&&(S(P),x(null))}catch(P){w.current===N&&N.epoch===E&&x(P.message)}finally{w.current===N&&(N.read=null,d(!1),N.again&&!N.mutating&&(N.again=!1,b.current()))}})();return N.read=j,j},[e,t,n]);b.current=C;const k=g.useCallback(async N=>{const E=w.current;if(!n||E.sessionId!==t)throw new Error("Cloud workspace unavailable");const j=N.action==="bind",P=["repositories","branches"].includes(N.action);if(j&&E.mutating)throw new Error("工作区操作正在进行");j&&(E.mutating=!0,E.epoch++,E.again=!1,p(!0),x(null));try{const D=await e.cloudWorkspace({...N,sessionId:t});return w.current===E&&v.current.sessionId===t&&(S(D),P||x(null)),D}catch(D){throw w.current===E&&!P&&x(D.message),D}finally{j&&w.current===E&&(E.mutating=!1,p(!1),(N.action==="bind"||E.again)&&(E.again=!1,b.current()))}},[e,t,n]);return g.useEffect(()=>{const N={api:e,sessionId:t,enabled:n,epoch:0,read:null,again:!1,mutating:!1};return w.current=N,_.current!==t&&(_.current=t,a(null),c(i??null)),x(null),p(!1),d(!1),n&&b.current(),()=>{N.epoch++,w.current===N&&(w.current={...N,enabled:!1,again:!1})}},[e,t,n]),g.useEffect(()=>{if(!n||!r)return;const N=r.on("session:event",j=>{var D;const P=j;P.sessionId===t&&((D=P.event)==null?void 0:D.kind)==="session_init"&&b.current()}),E=r.on("daemon:connected",()=>{b.current()});return()=>{N(),E()}},[r,t,n]),{workspace:o,binding:l,branchIntent:s,loading:u,busy:f,error:m,refresh:C,run:k}}var Am="Popover",[sj]=ro(Am,[Fl]),hd=Fl(),[cue,ao]=sj(Am),oj=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,a=hd(t),l=g.useRef(null),[c,u]=g.useState(!1),[d,f]=Bl({prop:r,defaultProp:i??!1,onChange:s,caller:Am});return h.jsx(sm,{...a,children:h.jsx(cue,{scope:t,contentId:bi(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:g.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:c,onCustomAnchorAdd:g.useCallback(()=>u(!0),[]),onCustomAnchorRemove:g.useCallback(()=>u(!1),[]),modal:o,children:n})})};oj.displayName=Am;var aj="PopoverAnchor",uue=g.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=ao(aj,n),s=hd(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:a}=i;return g.useEffect(()=>(o(),()=>a()),[o,a]),h.jsx(om,{...s,...r,ref:t})});uue.displayName=aj;var lj="PopoverTrigger",cj=g.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=ao(lj,n),s=hd(n),o=Ot(t,i.triggerRef),a=h.jsx(wt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":pj(i.open),...r,ref:o,onClick:Ie(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:h.jsx(om,{asChild:!0,...s,children:a})});cj.displayName=lj;var Nb="PopoverPortal",[due,hue]=sj(Nb,{forceMount:void 0}),uj=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=ao(Nb,t);return h.jsx(due,{scope:t,forceMount:n,children:h.jsx(Jr,{present:n||s.open,children:h.jsx(am,{asChild:!0,container:i,children:r})})})};uj.displayName=Nb;var El="PopoverContent",dj=g.forwardRef((e,t)=>{const n=hue(El,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=ao(El,e.__scopePopover);return h.jsx(Jr,{present:r||s.open,children:s.modal?h.jsx(pue,{...i,ref:t}):h.jsx(mue,{...i,ref:t})})});dj.displayName=El;var fue=fl("PopoverContent.RemoveScroll"),pue=g.forwardRef((e,t)=>{const n=ao(El,e.__scopePopover),r=g.useRef(null),i=Ot(t,r),s=g.useRef(!1);return g.useEffect(()=>{const o=r.current;if(o)return m_(o)},[]),h.jsx(cm,{as:fue,allowPinchZoom:!0,children:h.jsx(hj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ie(e.onCloseAutoFocus,o=>{var a;o.preventDefault(),s.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Ie(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,c=a.button===2||l;s.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:Ie(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),mue=g.forwardRef((e,t)=>{const n=ao(El,e.__scopePopover),r=g.useRef(!1),i=g.useRef(!1);return h.jsx(hj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var o,a;(o=e.onCloseAutoFocus)==null||o.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{var l,c;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(o))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),hj=g.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:o,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...d}=e,f=ao(El,n),p=hd(n);return i_(),h.jsx(em,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:h.jsx(Ku,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>f.onOpenChange(!1),children:h.jsx(f_,{"data-state":pj(f.open),role:"dialog",id:f.contentId,...p,...d,ref:t,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),fj="PopoverClose",gue=g.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=ao(fj,n);return h.jsx(wt.button,{type:"button",...r,ref:t,onClick:Ie(e.onClick,()=>i.onOpenChange(!1))})});gue.displayName=fj;var vue="PopoverArrow",xue=g.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=hd(n);return h.jsx(p_,{...i,...r,ref:t})});xue.displayName=vue;function pj(e){return e?"open":"closed"}var yue=oj,_ue=cj,bue=uj,mj=dj;const gj=yue,vj=_ue,Tb=g.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},i)=>h.jsx(bue,{children:h.jsx(mj,{ref:i,align:t,sideOffset:n,className:re("z-50 w-72 rounded-md border border-border bg-elevated p-4 text-text-100 shadow-md outline-none",e),...r})}));Tb.displayName=mj.displayName;const Wi="flex w-full min-w-0 items-center gap-2.5 rounded-md px-1.5 py-2 text-left text-[13px] hover:bg-text-100/5 disabled:opacity-40";function IE({title:e,children:t,trailing:n}){const[r,i]=g.useState(!0);return h.jsxs("section",{className:"rounded-xl border border-border bg-bg-0 p-3.5",children:[h.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[h.jsxs("button",{onClick:()=>i(!r),className:"flex items-center gap-1.5 py-0.5 text-[12px] font-medium text-text-200","aria-expanded":r,children:[e,h.jsx(Pn,{className:`h-3 w-3 text-text-400 ${r?"":"-rotate-90"}`})]}),n]}),r&&t]})}const wue=6e4,xj=300;function yj({message:e,onRetry:t}){return h.jsxs("div",{role:"alert",className:"m-2 rounded-md bg-error/5 p-2 text-[11px] leading-relaxed text-error",children:[e,h.jsx("button",{className:"ml-2 underline",onClick:t,children:"重试"})]})}function _j({controller:e,compact:t=!1}){const{binding:n,run:r,busy:i}=e,[s,o]=g.useState(!1),[a,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState([]),[p,m]=g.useState(1),[x,w]=g.useState(!1),[v,_]=g.useState(!1),[b,S]=g.useState(null),[C,k]=g.useState(0),N=g.useRef(!1),E=g.useRef(new Map);return g.useEffect(()=>{if(a===c)return;const j=setTimeout(()=>{u(a),m(1)},xj);return()=>clearTimeout(j)},[a,c]),g.useEffect(()=>{if(!s||n)return;const j=c+"|"+p,P=M=>{w(M.hasMore),f(L=>p===1?M.repos:[...L,...M.repos])},D=E.current.get(j);S(null);const R=N.current;if(N.current=!1,D&&Date.now()-D.at<wue&&!R){P(D),_(!1);return}let A=!1;return _(!0),r({action:"repositories",page:p,search:c}).then(M=>{if(A)return;const L={at:Date.now(),repos:M.repositories??[],hasMore:M.hasMore??!1};E.current.set(j,L),P(L)}).catch(M=>{A||S(M.message)}).finally(()=>{A||_(!1)}),()=>{A=!0}},[s,n,c,p,C,r]),n?h.jsxs("button",{className:t?"flex min-w-0 items-center gap-1.5 text-[11px] text-text-300 hover:text-text-100":Wi,title:n.owner+"/"+n.name,"aria-label":"在 GitHub 查看仓库",onClick:()=>window.open(`https://github.com/${n.owner}/${n.name}`,"_blank","noopener"),children:[h.jsx(wg,{className:"h-4 w-4 shrink-0 text-text-400"}),h.jsx("span",{className:"truncate",children:n.name}),!t&&h.jsx(wu,{className:"ml-auto h-3 w-3 text-text-400"})]}):h.jsxs(gj,{open:s,onOpenChange:j=>{o(j),j||(m(1),l(""),u(""))},children:[h.jsx(vj,{asChild:!0,children:h.jsxs("button",{disabled:i,className:t?"flex items-center gap-1.5 text-[11px] text-text-300":Wi,"aria-label":"添加或选择仓库",children:[h.jsx(wg,{className:"h-4 w-4 text-text-400"}),h.jsx("span",{className:"flex-1",children:"添加 repo"}),!t&&h.jsx(o4,{className:"h-3.5 w-3.5 text-text-400"})]})}),h.jsxs(Tb,{align:"end",className:"w-[330px] p-1.5",children:[h.jsxs("div",{className:"flex items-center gap-2 border-b border-border p-2",children:[h.jsx(zf,{className:"h-3.5 w-3.5 text-text-400"}),h.jsx("input",{autoFocus:!0,"aria-label":"搜索仓库",placeholder:"搜索 GitHub 仓库…",value:a,onChange:j=>l(j.target.value),className:"w-full bg-transparent text-[12px] outline-none"})]}),h.jsxs("div",{className:"max-h-[340px] overflow-y-auto py-1",children:[d.map(j=>h.jsxs("button",{disabled:i,className:Wi,onClick:()=>{S(null),r({action:"bind",repoId:j.repoId,branch:j.defaultBranch}).then(()=>o(!1)).catch(P=>S(P.message))},children:[h.jsx(wg,{className:"h-4 w-4 shrink-0 text-text-400"}),h.jsxs("span",{className:"truncate text-[12px]",children:[j.owner,"/",j.name]})]},j.repoId)),b&&h.jsx(yj,{message:b,onRetry:()=>{N.current=!0,k(j=>j+1)}}),!v&&!b&&!d.length&&h.jsx("p",{className:"p-3 text-[12px] text-text-400",children:"没有找到仓库"}),v&&h.jsxs("div",{className:"flex items-center gap-2 p-3 text-[12px] text-text-400",children:[h.jsx(Tn,{className:"h-3 w-3 animate-spin"}),"正在读取…"]}),x&&!v&&h.jsx("button",{className:Wi,onClick:()=>m(j=>j+1),children:"加载更多"})]})]})]})}function bj({controller:e,compact:t=!1,disabled:n=!1}){const{binding:r,workspace:i,branchIntent:s,run:o,busy:a}=e,[l,c]=g.useState(!1),[u,d]=g.useState(""),[f,p]=g.useState(""),[m,x]=g.useState([]),[w,v]=g.useState(1),[_,b]=g.useState(),[S,C]=g.useState(),[k,N]=g.useState(!1),[E,j]=g.useState(!1),[P,D]=g.useState(null),[R,A]=g.useState(0),M=u.trim();g.useEffect(()=>{if(M===f)return;if(!M){p("");return}const O=setTimeout(()=>p(M),xj);return()=>clearTimeout(O)},[M,f]),g.useEffect(()=>{if(!l||!r||M!==f)return;let O=!1;return D(null),j(!0),o({action:"branches",repoId:r.repoId,...f?{search:f,..._?{cursor:_}:{}}:{page:w}}).then(I=>{O||(x(U=>(f?!_:w===1)?I.branches??[]:[...U,...I.branches??[]]),N(!!(I.hasMore&&(!f||I.nextCursor))),C(I.nextCursor))}).catch(I=>{O||D(I.message)}).finally(()=>{O||j(!1)}),()=>{O=!0}},[l,r==null?void 0:r.repoId,M,f,w,_,R,o]);const L=O=>{c(O),O||(d(""),p(""),x([]),v(1),b(void 0),C(void 0),N(!1),j(!1),D(null))},z=s??(i==null?void 0:i.actualBranch)??(i?"HEAD · "+i.head.slice(0,7):(r==null?void 0:r.sourceBranch)??"选择 branch"),F=[...new Set([...[...r?[r.defaultBranch]:[],...i!=null&&i.actualBranch?[i.actualBranch]:[],...(i==null?void 0:i.branches)??[]].filter(O=>O.toLowerCase().includes(M.toLowerCase())),...m])],$=O=>{const I=O===((i==null?void 0:i.actualBranch)??(r==null?void 0:r.sourceBranch));o(I?{action:"intend"}:{action:"intend",branch:O}).then(()=>{L(!1)}).catch(()=>{})};return h.jsxs(gj,{open:l,onOpenChange:L,children:[h.jsx(vj,{asChild:!0,children:h.jsxs("button",{className:t?"flex min-w-0 items-center gap-1.5 text-[11px] text-text-300 disabled:opacity-40":Wi,"aria-label":`选择分支,当前 ${z}`,disabled:a||n,children:[h.jsx(Su,{className:"h-3.5 w-3.5 shrink-0 text-text-400"}),h.jsx("span",{className:"truncate",children:z}),h.jsx(Pn,{className:"ml-auto h-3 w-3 shrink-0 text-text-400"})]})}),h.jsxs(Tb,{align:"end",className:"w-[280px] p-1.5",children:[h.jsxs("div",{className:"flex items-center gap-2 border-b border-border p-2",children:[h.jsx(zf,{className:"h-3.5 w-3.5 text-text-400"}),h.jsx("input",{autoFocus:!0,"aria-label":"搜索分支",placeholder:"搜索分支…",value:u,maxLength:100,onChange:O=>{d(O.target.value),O.target.value.trim()!==M&&(x([]),v(1),b(void 0),C(void 0),N(!1),D(null),j(!0))},className:"w-full bg-transparent text-[12px] outline-none"})]}),h.jsxs("div",{className:"max-h-[300px] overflow-y-auto",children:[(M===f?F:[]).map(O=>h.jsxs("button",{className:Wi,onClick:()=>$(O),children:[h.jsx(Su,{className:"h-3.5 w-3.5 text-text-400"}),h.jsx("span",{className:"flex-1 truncate",children:O}),O===(r==null?void 0:r.defaultBranch)&&h.jsx("span",{className:"text-[10px] text-text-400",children:"默认"}),O===z&&h.jsx(Zo,{className:"h-3.5 w-3.5"})]},O)),P&&h.jsx(yj,{message:P,onRetry:()=>A(O=>O+1)}),E&&h.jsxs("div",{role:"status",className:"flex items-center gap-2 p-3 text-[12px] text-text-400",children:[h.jsx(Tn,{className:"h-3 w-3 animate-spin"}),"正在读取…"]}),!E&&!P&&!F.length&&h.jsx("p",{className:"p-3 text-[12px] text-text-400",children:"没有找到分支"}),k&&h.jsx("button",{className:Wi,disabled:E||!!P,onClick:()=>{j(!0),f?b(S):v(O=>O+1)},children:"加载更多分支"})]})]})]})}function Sue({controller:e,disabled:t=!1}){return h.jsxs("div",{"data-testid":"workspace-input-chip",className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 px-1 pb-2 text-text-300",children:[h.jsx("div",{className:"max-w-[200px] min-w-0",children:h.jsx(_j,{controller:e,compact:!0})}),e.binding&&h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"h-3 w-px bg-border"}),h.jsx("div",{className:"min-w-0 max-w-[230px]",children:h.jsx(bj,{controller:e,compact:!0,disabled:t},e.binding.repoId)})]}),e.loading&&h.jsx(Tn,{className:"h-3 w-3 shrink-0 animate-spin text-text-400"})]})}function kue({controller:e,disabled:t=!1}){var x;const{binding:n,workspace:r,branchIntent:i,loading:s,busy:o,error:a,refresh:l,run:c}=e,[u,d]=g.useState(null),[f,p]=g.useState();g.useEffect(()=>{if(!u){p(void 0);return}let w=!1;return p(void 0),c({action:"diff",filePath:u}).then(v=>{w||p(v.diff)}).catch(()=>{}),()=>{w=!0}},[u,c]);const m=(x=r==null?void 0:r.files.find(w=>w.path===u))==null?void 0:x.comparison;return h.jsxs("div",{className:"space-y-3",children:[h.jsxs(IE,{title:"环境",trailing:h.jsx("button",{"aria-label":"刷新工作区",title:"刷新工作区",disabled:o||s,onClick:()=>void l(),className:"p-1 text-text-400 disabled:opacity-40",children:h.jsx(bF,{className:`h-3 w-3 ${s?"animate-spin":""}`})}),children:[h.jsxs("div",{className:"flex items-center gap-2.5 px-1.5 py-2 text-[13px]",children:[h.jsx(E7,{className:"h-4 w-4 text-text-400"}),h.jsx("span",{children:"云端"}),h.jsx("span",{className:"ml-auto text-[11px] text-text-400",children:n?"已关联":"待关联"})]}),h.jsx(_j,{controller:e}),n&&h.jsx(bj,{controller:e,disabled:t},n.repoId),i&&h.jsxs("p",{className:"mt-1 px-1.5 text-[11px] text-text-400",children:["将在下一条消息里让 agent 切换到 ",i]}),r&&h.jsxs("p",{className:"mt-1 px-1.5 text-[10px] text-text-400",children:["截至 ",FH(new Date(r.measuredAt).toISOString())," ·"," ",r.head.slice(0,7)]}),!n&&h.jsx("p",{className:"mt-2 px-1.5 text-[11px] leading-relaxed text-text-400",children:"关联仓库和分支,在这个会话的独立工作区里开发。"}),a&&h.jsxs("div",{role:"alert",className:"mt-2 rounded-md bg-error/5 p-2 text-[11px] leading-relaxed text-error",children:[a,h.jsx("button",{className:"ml-2 underline",onClick:()=>void l(),children:"重试读取"})]})]}),!!(r!=null&&r.files.length)&&h.jsxs(IE,{title:"Changes",trailing:h.jsxs("span",{className:"text-[10px] text-text-400",children:[r.totalFiles??r.files.length," 个文件"]}),children:[h.jsxs("button",{"aria-label":"查看全部改动",className:Wi,onClick:()=>d(r.files[0].path),children:[h.jsx(L7,{className:"h-4 w-4 text-text-400"}),h.jsxs("span",{className:"tabular-nums text-success",children:["+",r.added]}),h.jsxs("span",{className:"tabular-nums text-error",children:["−",r.removed]}),h.jsx(e4,{className:"ml-auto h-3 w-3 text-text-400"})]}),h.jsx("div",{className:"mb-2",children:r.files.map(w=>h.jsxs("button",{className:"flex w-full min-w-0 items-center gap-2 rounded-md px-1.5 py-1.5 text-left text-[11px] hover:bg-text-100/5",onClick:()=>d(w.path),children:[h.jsx("span",{className:"w-4 shrink-0 text-[10px] text-text-400",children:w.status}),h.jsx("span",{title:w.path,className:"min-w-0 flex-1 truncate text-text-300",children:w.path.split("/").at(-1)}),h.jsxs("span",{className:"text-success",children:["+",w.added]}),h.jsxs("span",{className:"text-error",children:["−",w.removed]})]},w.path))}),r.filesTruncated&&h.jsx("p",{className:"mb-2 px-1 text-[11px] text-text-400",children:"仅展示前 200 个改动文件。"})]}),h.jsx(ej,{open:u!==null,onOpenChange:w=>{w||d(null)},children:h.jsxs(Eb,{className:"flex h-[min(680px,84vh)] w-[min(1080px,94vw)] max-w-none flex-col gap-0 overflow-hidden p-0",children:[h.jsxs("div",{className:"border-b border-border px-5 py-4",children:[h.jsx(Ib,{className:"text-[14px]",children:"代码改动"}),h.jsxs(rj,{className:"mt-2 text-[11px]",children:[(r==null?void 0:r.actualBranch)??"HEAD"," ·"," ",m==="index"?"暂存区相对当前提交的改动":m==="head"?"尚未提交的改动":"相对起始提交 "+(r==null?void 0:r.initialCommit.slice(0,7))+" 的累计改动"]})]}),h.jsxs("div",{className:"flex min-h-0 flex-1",children:[h.jsx("nav",{"aria-label":"改动文件",className:"w-[225px] shrink-0 overflow-auto border-r border-border bg-bg-50 p-2 max-[700px]:hidden",children:r==null?void 0:r.files.map(w=>h.jsx("button",{className:Wi+" text-[11px]",onClick:()=>d(w.path),children:h.jsx("span",{className:"truncate",children:w.path.split("/").at(-1)})},w.path))}),h.jsxs("div",{className:"min-w-0 flex-1 overflow-auto",children:[h.jsx("div",{className:"sticky top-0 border-b border-border bg-bg-50 px-4 py-3 font-mono text-[11px]",children:u}),f?f.binary?h.jsx("p",{className:"p-5 text-[12px] text-text-400",children:"二进制文件发生变化"}):f.notStored?h.jsx("p",{className:"p-5 text-[12px] text-text-400",children:"这个文件的补丁暂不可用(文件较多或体积较大时只保存部分补丁)。"}):h.jsxs("pre",{className:"min-w-fit py-2 font-mono text-[11px] leading-6",children:[f.patch.split(`
623
+ `).map((w,v)=>h.jsx("div",{className:`px-4 ${w.startsWith("+")?"bg-success/8 text-success":w.startsWith("-")?"bg-error/8 text-error":"text-text-300"}`,children:w||" "},v)),f.truncated&&h.jsx("div",{className:"px-4 text-text-400",children:"Diff 较大,已截断显示。"})]}):h.jsx("div",{className:"p-5 text-[12px] text-text-400",children:a??"正在读取 diff…"})]})]})]})})]})}const Cue=250;function Eue(e){if(!e||!Number.isFinite(e))return null;const t=e/1e3;if(t<60)return`${t.toFixed(0)}s`;const n=Math.floor(t/60);return`${n}m${Math.round(t-n*60).toString().padStart(2,"0")}s`}function Iue({agents:e}){var l,c,u;const[t,n]=g.useState(!1),r=g.useRef(null);if(g.useEffect(()=>{if(!t)return;const d=f=>{const p=r.current;p&&f.target instanceof Node&&p.contains(f.target)||n(!1)};return window.addEventListener("pointerdown",d,!0),()=>window.removeEventListener("pointerdown",d,!0)},[t]),e.length===0)return null;const i=e.length===1?e[0]:null,s=i?i.description:`${e.length} 个后台任务`,o=i?Eue((c=(l=i.progress)==null?void 0:l.stats)==null?void 0:c.durationMs):null,a=i?(u=i.progress)==null?void 0:u.lastToolName:null;return h.jsxs("div",{ref:r,"data-testid":"running-agents-chip","data-agent-count":e.length,className:"relative",children:[t?h.jsx("div",{"data-testid":"running-agents-popover",className:"absolute bottom-full right-0 z-20 mb-1 w-[min(560px,80vw)]",children:h.jsx("div",{className:"min-w-0 overflow-y-auto rounded-lg border border-bg-200/60 bg-bg-100 px-2 py-1 shadow-lg",style:{maxHeight:Cue},children:e.map(d=>h.jsx(SM,{expandable:!1,description:d.description,input:d.input,output:d.output,...d.error!==void 0?{error:d.error}:{},pending:d.pending,notifications:d.notifications,...d.toolResultExtra?{toolResultExtra:d.toolResultExtra}:{},...d.progress?{progress:d.progress}:{}},d.toolUseId))})}):null,h.jsxs("button",{type:"button","data-testid":"running-agents-chip-toggle","aria-expanded":t,onClick:()=>n(d=>!d),className:re("flex max-w-[min(560px,80vw)] min-w-0 items-center gap-2 rounded-full","border border-bg-200/60 bg-bg-100/95 px-3 py-1 text-[12px] shadow-md backdrop-blur","hover:bg-bg-200/95 transition-colors"),children:[h.jsx(Tn,{className:"w-3 h-3 shrink-0 animate-spin text-blue-400"}),h.jsx("span",{className:"min-w-0 flex-1 truncate text-left text-text-200",children:s}),o?h.jsx("span",{className:"shrink-0 tabular-nums text-text-400",children:o}):null,a?h.jsxs("span",{className:"shrink-0 font-mono tabular-nums text-blue-400",children:["now:",a]}):null,h.jsx(t4,{className:re("w-3.5 h-3.5 shrink-0 text-text-400 transition-transform",t&&"rotate-180")})]})]})}const Nue={closeTrailing:!1},Tue={closeTrailing:!0};function Pue(e){return e?Nue:Tue}function Rue({session:e,api:t,onPromoteQuickAsk:n}){const r=KP(e.sessionId);return h.jsx(wj,{state:r,extras:{session:e,api:t,...n?{onPromoteQuickAsk:n}:{}}})}function Mue({headerMeta:e,connState:t,liveWorktreeRoot:n,onOpenConfig:r,variant:i="full",ephemeral:s,onPromote:o,hideHeader:a=!1,flatProcess:l=!1,lines:c,pendingPermissions:u,procAlive:d,rewindableUserMessageIds:f,onPermissionRespond:p,onPermissionInterrupt:m,onRewind:x,onFork:w,onQuickAsk:v,topSlot:_,codexHistory:b,realtimeQuestionAnswers:S,onSubmitQuestion:C,onCancelQuestion:k,liveQuestionToolUseIds:N,api:E,cwd:j,tool:P,cloudVolume:D,sessionKey:R,onSend:A,awaitingUser:M,queued:L,onDequeue:z,onAbort:F,onNewSession:$,onClearSession:O,configSlot:I,workspaceInput:U,workspaceInputDisabled:V,chatRootRef:B,chatBodyRef:ne,drawers:ae,xtermSlot:Y,fileSharingScope:ye,onShareFile:Ce,onOpenInTab:oe,onPreviewMarkdown:je,onOpenFilePath:Me,dispatchOrigin:De}){const[xe,Ke]=g.useState(0),rt=g.useMemo(()=>i==="full"?gY(XP(c)):[],[c,i]),Ze=g.useMemo(()=>new Set(rt.map(ht=>ht.toolUseId)),[rt]);return h.jsx(uie,{children:h.jsxs("div",{ref:B,"data-cc-chat-root":"",className:"flex flex-col h-full bg-bg-100",children:[a?null:h.jsx(lse,{meta:e,...P?{tool:P}:{},...D?{cloudVolume:D}:{},connState:t,variant:i,...n!==void 0?{liveWorktreeRoot:n}:{},...i==="full"&&r?{onOpenConfig:r}:{},...i==="quickask"?{ephemeral:s??!1,...o?{onPromote:o}:{}}:{}}),h.jsx("div",{ref:ne,"data-testid":"chat-body",className:"flex-1 overflow-y-auto min-h-0",style:{overflowAnchor:"none",paddingBottom:xe},children:h.jsx(CM,{lines:c,forkByTurn:P==="codex",...p?{onPermissionRespond:p}:{},...m&&d?{onPermissionInterrupt:m}:{},topSlot:_,codexHistory:b,...x?{onRewind:x}:{},rewindableUserMessageIds:f,...w?{onFork:w}:{},...v?{onQuickAsk:v}:{},realtimeQuestionAnswers:S,onSubmitQuestion:C,...k?{onCancelQuestion:k}:{},liveQuestionToolUseIds:N,...ye?{fileSharingScope:ye}:{},...Ce?{onShareFile:Ce}:{},...oe?{onOpenInTab:oe}:{},...je?{onPreviewMarkdown:je}:{},...Me?{onOpenFilePath:Me}:{},...De?{dispatchOrigin:De}:{},...i==="full"&&!l?{turnCollapse:Pue(d)}:{},dockedAgentToolUseIds:Ze})}),Y,h.jsx(aue,{onHeightChange:Ke,children:h.jsx(Iue,{agents:rt})}),e.larkChatName?h.jsx("div",{className:"mx-3 mb-3 rounded-lg border border-border bg-bg-200 px-3 py-2 text-[12px] text-text-400","data-testid":"lark-readonly-notice",children:e.larkChatType==="p2p"?`此会话由与「${e.larkChatName}」的飞书私聊驱动——对方消息触发,这里仅供观察。`:`此会话由飞书群「${e.larkChatName}」驱动——群成员 @ bot 提问触发,这里仅供观察。`}):h.jsx(ose,{meta:e,aboveSlot:U,disabled:V,...E?{api:E}:{},cwd:j,...P?{tool:P}:{},sessionKey:R,onSend:A,awaitingUser:M,...L?{queued:L}:{},...z?{onDequeue:z}:{},...F?{onAbort:F}:{},...$?{onNewSession:$}:{},...O?{onClearSession:O}:{},...I?{configSlot:I}:{}}),ae]})})}function wj({state:e,extras:t,onQuickAskInternal:n,onPreviewMdInternal:r}){var xr;const{session:i,api:s,liveGitBranch:o,liveWorktreeRoot:a,cloudVolume:l,onNewSession:c,onTurnEnd:u,onOpenConfig:d,onFork:f,onQuickAsk:p,viewerRole:m,onPromoteQuickAsk:x,configSlot:w,hideHeader:v,flatProcess:_}=t,{capabilities:b}=Im(i.tool||"claude"),S=(b==null?void 0:b.features)??VT(i.tool),[C,k]=g.useState(null),[N,E]=g.useState(null),j=Yp(),P=!!s&&j.actionsLevel==="owner"&&S.fileSharing,D=ZT(i.ownerPersonaId??null).persona,R=(D==null?void 0:D.label)??null,A=!!R&&!!i.ownerPersonaId,M=rue(),L=g.useMemo(()=>({resolve:(Z,we)=>M.resolve(Z,we,i.sessionId),...M.onOpenSession?{onOpenSession:M.onOpenSession}:{}}),[M,i.sessionId]),z=g.useCallback((Z,we)=>{k({kind:Z,text:we}),setTimeout(()=>{k(Ae=>(Ae==null?void 0:Ae.text)===we?null:Ae)},2e3)},[]),F=Ni(),$=ox(i.tool)&&m!=="guest"&&!i.larkChatId&&!x,O=lue(s,i.sessionId,$,F,i.cloudWorkspace,i.cloudBranchIntent),I=fz(),U=HP(i.sessionId,i.toolSessionId),{events:V,pendingQuestions:B,clearQuestion:ne,markQuestionSubmitted:ae,status:Y}=U,ye=e.historyLoading,Ce=VP(Y);g.useEffect(()=>{Oe("chat-panel","sessionStatus",{sessionId:i.sessionId,sessionStatus:Y,procAlive:Ce})},[Y,Ce,i.sessionId]);const oe=e.lines,je=e.pendingPermissions,Me=je[0]??null,De=g.useMemo(()=>pY(V),[V]),[xe,Ke]=g.useState(null),[rt,Ze]=g.useState(()=>new Set);dY(s,i.sessionId,i.toolSessionId,S.observe);const ht=g.useRef(i.sessionId);g.useEffect(()=>{if(ht.current=i.sessionId,!S.rewind){Ke(null);return}let Z=!1;return Ke(null),(async()=>{try{const we=await s.sessionRewindableMessageIds(i.sessionId);if(Z)return;Ke(new Set(we.userMessageIds))}catch{Z||Ke(null)}})(),()=>{Z=!0}},[s,i.sessionId,S.rewind]);const Kt=g.useCallback(()=>{const Z=i.sessionId;s.sessionRewindableMessageIds(Z).then(we=>{ht.current===Z&&Ke(new Set(we.userMessageIds))}).catch(()=>{})},[s,i.sessionId]),ue=g.useMemo(()=>{if(xe!==null){const lt=new Set(xe);for(const Or of rt)lt.delete(Or);return lt}const Z=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),we=new Set;let Ae=null;for(const lt of oe)lt.kind==="user-text"?Ae=lt.uuid??null:Ae&&lt.kind==="tool-call"&&Z.has(lt.tool)&&!rt.has(Ae)&&we.add(Ae);return we},[oe,rt,xe]),ze=g.useRef(u);ze.current=u,hY(i.sessionId,i.toolSessionId,()=>{hn(null),Ze(new Set)});const ke=kse({sessionStatus:Y}),Fe=g.useRef(null);g.useEffect(()=>{var Ae;const Z=Fe.current,we=(Z==null?void 0:Z.sid)===i.sessionId;we&&Z.phase===ke||(Fe.current={sid:i.sessionId,phase:ke},Oe("session-phase",ke,{sid:i.sessionId,phase:ke,prev:we?Z.phase:null,desc:Sse[ke]}),we&&Z.phase==="turn-running"&&ke!=="turn-running"&&((Ae=ze.current)==null||Ae.call(ze),Kt()))},[ke,i.sessionId,Kt]);const yt=g.useCallback(async()=>{const Z=await s.sessionInterrupt(i.sessionId).catch(()=>{});return(Z==null?void 0:Z.queued)??[]},[s,i.sessionId]),[tn,hn]=g.useState(null),W=g.useCallback(Z=>{hn(Z)},[]),[ee,be]=g.useState(!1),Le=g.useCallback(()=>{s.sessionStop(i.sessionId).catch(()=>{}),be(!1)},[s,i.sessionId]);g.useCallback(Z=>{s.pinSession(i.sessionId,Z).catch(we=>{Oe("chat-panel","pinSession failed",{err:we==null?void 0:we.message})})},[s,i.sessionId]);const He=x?"quickask":"full",{container:At,workspaceContainer:bn,onCollapse:nn,hostExtras:fn}=mse(),le=g.useRef(0),Se=g.useRef(null);g.useEffect(()=>{const Z=we=>{if(we.key!=="Escape")return;if(!Ce){le.current=0;return}if(we.isComposing)return;const lt=we.target;if(lt&&lt.closest("[data-cc-chat-root]")!==Se.current)return;const Or=Date.now();Or-le.current<2e3?(le.current=0,be(!0)):(le.current=Or,yt())};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[yt,Ce]);const it=g.useRef(null),mt=g.useRef(null),gr=g.useRef(!!e.codexHistory);gr.current=!!e.codexHistory;const se=g.useRef(!0),nt=g.useRef(void 0),Bt=g.useRef(0),ti=g.useRef(0),sa=g.useRef(void 0);g.useEffect(()=>{E(null)},[i.sessionId]),g.useEffect(()=>{const Z=it.current;if(!Z)return;const we=150,Ae=lt=>{gr.current||Date.now()<ti.current&&(lt.preventDefault(),ti.current=Date.now()+we)};return Z.addEventListener("wheel",Ae,{passive:!1}),()=>Z.removeEventListener("wheel",Ae)},[]),g.useEffect(()=>{const Z=it.current;if(!Z)return;const we=32,Ae=()=>{var Or;const lt=Z.scrollHeight-Z.scrollTop-Z.clientHeight;se.current=lt<=we,e.codexHistory&&(mt.current=p2(Z)),Z.scrollTop<=24&&e.historyHasMore&&!e.historyLoadingOlder&&!e.historyError&&!ye&&((Or=e.loadOlderHistory)==null||Or.call(e))};return Z.addEventListener("scroll",Ae,{passive:!0}),()=>Z.removeEventListener("scroll",Ae)},[e.codexHistory,e.historyHasMore,e.historyLoadingOlder,e.historyError,e.loadOlderHistory,ye]),g.useLayoutEffect(()=>{var Pb;const Z=it.current;if(!Z)return;const we=sa.current!==i.sessionId;we&&(sa.current=i.sessionId,se.current=!0,nt.current=void 0,Bt.current=0,ti.current=0,mt.current=null);const Ae=nt.current,lt=(Pb=oe[0])==null?void 0:Pb.seq;if(nt.current=lt,e.codexHistory){!we&&mt.current&&!se.current?Tie(Z,mt.current):se.current&&(Z.scrollTop=Z.scrollHeight),mt.current=p2(Z),Bt.current=Z.scrollHeight-Z.scrollTop;return}!we&&Ae!==void 0&&lt!==void 0&&lt<Ae?(Z.scrollTop=Z.scrollHeight-Bt.current,ti.current=Date.now()+200):se.current&&(Z.scrollTop=Z.scrollHeight),Bt.current=Z.scrollHeight-Z.scrollTop},[oe,Me==null?void 0:Me.requestId,i.sessionId]);const oa=g.useMemo(()=>{const Z={};for(const[we,Ae]of Object.entries(B))Ae.submittedAnswers&&(Z[we]=Ae.submittedAnswers);return Z},[B]),hs=g.useMemo(()=>new Set(Object.keys(B)),[B]),aa=g.useCallback(async(Z,we)=>{try{await s.answerQuestion({sessionId:i.sessionId,toolUseId:Z,answers:we}),ae(Z,we)}catch{}},[s,i.sessionId,ae]),Gl=g.useCallback(async Z=>{try{await s.cancelQuestion({sessionId:i.sessionId,toolUseId:Z}),ne(Z)}catch{}},[s,i.sessionId,ne]),Yl=g.useCallback(async(Z,we)=>{var Ae;if(Me)try{await((Ae=e.respondPermission)==null?void 0:Ae.call(e,Me.requestId,Z?"allow":"deny"))}catch{}},[e,Me]),fs=g.useCallback(async()=>{const Z=i.sessionId;try{await s.sessionStop(Z)}catch{}e.clearSession?await e.clearSession():await s.sessionNew(Z)},[e,s,i.sessionId]),ni=e.meta.streamInProgress??!1,fd=g.useMemo(()=>{if(e.codexHistory)return h.jsxs("div",{className:"flex flex-col items-center gap-2 py-2 text-xs text-text-400","data-testid":"codex-history-top",children:[e.historySyncError?h.jsx("span",{children:e.historySyncError}):null,e.historyError?h.jsx("span",{"data-testid":"history-error",children:e.historyError}):null,ye||e.historyLoadingOlder?h.jsx("span",{"data-testid":"history-loading",children:"正在加载历史…"}):e.historyHasMore?h.jsx("button",{type:"button",onClick:()=>{var we;return void((we=e.loadOlderHistory)==null?void 0:we.call(e))},children:e.historyError?"重试更早记录":"加载更早记录"}):e.historyLoaded&&!e.historyError&&!e.historySyncError?h.jsx("span",{children:"已加载全部轮次摘要"}):null,e.historyError||e.historySyncError?h.jsx("button",{type:"button",onClick:()=>{var we;return void((we=e.refreshHistory)==null?void 0:we.call(e))},children:"刷新历史"}):null]});const Z=e.historySyncError?h.jsxs("div",{className:"flex justify-center items-center gap-2 py-2 text-[12px] text-text-400","data-testid":"history-sync-error",children:[h.jsx("span",{children:e.historySyncError}),e.reloadFromCloud?h.jsx("button",{type:"button","data-testid":"history-sync-reload",disabled:ni,onClick:e.reloadFromCloud,className:"text-accent hover:underline cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 disabled:no-underline",children:"从云端重新加载"}):null]}):null;return e.historyError?h.jsxs(h.Fragment,{children:[Z,h.jsxs("div",{className:"flex justify-center py-2 text-[12px] text-text-400","data-testid":"history-error",children:["历史未加载完(",e.historyError,");切走再切回可重试"]})]}):Z||(ye&&oe.length===0?h.jsx("div",{className:"flex justify-center py-4","data-testid":"history-loading",children:h.jsx(Tn,{className:"w-4 h-4 text-text-400 animate-spin"})}):null)},[ye,oe.length,e.historyError,e.historySyncError,e.reloadFromCloud,ni,e.codexHistory,e.historyHasMore,e.historyLoaded,e.historyLoadingOlder,e.loadOlderHistory,e.refreshHistory]),la=e.meta,Gt=h.jsxs(h.Fragment,{children:[i.toolSessionId&&S.subagents?h.jsx(gse,{api:s,cwd:i.cwd,toolSessionId:i.toolSessionId,toolKind:i.tool??"claude"}):null,tn&&S.rewind?h.jsx(xse,{open:!0,onOpenChange:Z=>{Z||hn(null)},api:s,sessionId:i.sessionId,userMessageId:tn,lines:oe,procAlive:Ce,onNoChanges:Z=>{Ze(we=>{if(we.has(Z))return we;const Ae=new Set(we);return Ae.add(Z),Ae})}}):null,ee?h.jsx(Aue,{onConfirm:Le,onCancel:()=>be(!1)}):null]}),Xl={kind:"session",sessionId:i.sessionId},pd=g.useCallback(async Z=>{if(s)try{await dC(s,F,i.sessionId,Z)}catch(we){const Ae=we.message;Oe("chat-panel","open-in-tab failed",{err:Ae}),z("err",`Open in tab 失败:${Ae}`)}},[s,F,i.sessionId,z]),[jt,$t]=g.useState(!1),[Wn,vr]=g.useState(null),Mi=g.useCallback(Z=>{if(r){r(Z);return}vr(Z),$t(!0)},[r]),jm=g.useCallback(Z=>{if(!s)return;const we=async()=>{try{await s.attachmentGroupAdd(i.sessionId,Z)}catch(lt){Oe("chat-panel","file-link groupAdd skipped",{err:lt.message})}},Ae=lt=>{const Or=lt.message;Oe("chat-panel","file-link open failed",{err:Or}),z("err",`打开文件失败:${Or}`)};if(wm(Z)){we().then(()=>Mi(Z),Ae);return}dC(s,F,i.sessionId,Z,60,we).catch(Ae)},[s,F,i.sessionId,Mi,z]),md=g.useCallback(async Z=>{if(!s)throw new Error("daemon api not ready");const we=await F_(s,F,i.sessionId,Z,60),Ae=await fetch(we);if(!Ae.ok)throw new Error(`fetch ${Ae.status} ${Ae.statusText}`);return await Ae.text()},[s,F,i.sessionId]),lo=g.useCallback(async(Z,we)=>{if(s)try{const{url:Ae}=await s.attachmentSignUrl({sessionId:i.sessionId,relPath:Z,...we?{view:we}:{}}),lt=await JG(Ae);z(lt?"ok":"err",lt?"分享链接已复制到剪贴板":"复制失败:请手动复制")}catch(Ae){const lt=Ae.message;Oe("chat-panel","share-file failed",{err:lt}),z("err",`生成分享链接失败:${lt}`)}},[s,i.sessionId,z]),co=g.useCallback(()=>E(null),[]),Lm=N==="files"&&P&&s?{title:"Edited Files",onBack:co,content:h.jsx(Ble,{api:s,scope:Xl,sessionId:i.sessionId,onShareFile:lo,onOpenInTab:pd,onPreviewMarkdown:Mi})}:N==="cron"?{title:`定时任务${De.length?` (${De.length})`:""}`,onBack:co,content:h.jsx("div",{className:"p-3",children:h.jsx(wse,{jobs:De})})}:N==="persona"&&A&&s&&i.ownerPersonaId?{title:`Persona · ${R??""}`,onBack:co,content:h.jsx(eue,{personaId:i.ownerPersonaId,open:!0,onClose:co,api:s,embedded:!0,...m?{viewerRole:m}:{}},i.ownerPersonaId)}:null,gd=He==="full"?h.jsx(fse,{session:i,meta:la,...$&&O.binding?{liveGitBranch:((xr=O.workspace)==null?void 0:xr.actualBranch)??null}:o!==void 0?{liveGitBranch:o}:{},...a!==void 0?{liveWorktreeRoot:a}:{},...A?{personaName:R}:{},...A?{onOpenPersona:()=>E("persona")}:{},...P?{onOpenFiles:()=>E("files")}:{},cronActiveCount:De.length,onCronClick:()=>E("cron"),onForceStop:()=>be(!0),...ox(i.tool)&&e.reloadFromCloud?{onReloadFromCloud:e.reloadFromCloud,reloadFromCloudDisabled:ni}:{},...m?{viewerRole:m}:{},...b!=null&&b.toolSessionIdLabel?{toolSessionIdLabel:b.toolSessionIdLabel}:{},drill:Lm,...nn?{onCollapse:nn}:{},...fn?{title:fn.title,leadingEntries:fn.leadingEntries}:{}}):null;return h.jsxs(h.Fragment,{children:[$&&bn?Do.createPortal(h.jsx(kue,{controller:O,disabled:la.streamInProgress}),bn):null,At&&gd?Do.createPortal(gd,At):null,h.jsx(Mue,{headerMeta:la,workspaceInput:$?h.jsx(Sue,{controller:O,disabled:la.streamInProgress}):void 0,workspaceInputDisabled:$&&O.busy,connState:e.connState,...a!==void 0?{liveWorktreeRoot:a}:{},...d?{onOpenConfig:d}:{},variant:He,...v||$?{hideHeader:!0}:{},..._?{flatProcess:_}:{},...He==="quickask"?{ephemeral:i.ephemeral!==!1,onPromote:()=>void(x==null?void 0:x(i.sessionId))}:{},lines:oe,pendingPermissions:je,procAlive:Ce,rewindableUserMessageIds:ue,onPermissionRespond:Yl,onPermissionInterrupt:yt,onRewind:S.rewind?W:void 0,...f&&S.fork?{onFork:f}:{},...n&&S.fork?{onQuickAsk:n}:p&&S.fork?{onQuickAsk:p}:{},topSlot:fd,codexHistory:e.codexHistory,realtimeQuestionAnswers:oa,onSubmitQuestion:aa,onCancelQuestion:Gl,liveQuestionToolUseIds:hs,api:s,cwd:i.cwd,...i.tool?{tool:i.tool}:{},...l?{cloudVolume:l}:{},sessionKey:i.sessionId,onSend:e.sendText,queued:e.queued,onDequeue:e.dequeue,awaitingUser:je.length>0||Object.values(B).some(Z=>!Z.submittedAnswers),onAbort:yt,...c?{onNewSession:c}:{},onClearSession:fs,...w?{configSlot:w}:{},chatRootRef:Se,chatBodyRef:it,drawers:Gt,xtermSlot:I==="tui"&&Ce&&S.tui?h.jsx(Ole,{sessionId:i.sessionId,client:F},i.sessionId):null,fileSharingScope:Xl,...s?{onShareFile:lo}:{},...s?{onOpenInTab:pd}:{},...s?{onPreviewMarkdown:Mi}:{},...s?{onOpenFilePath:jm}:{},dispatchOrigin:L}),s?h.jsx(oue,{open:jt,onOpenChange:$t,relPath:Wn,loadMarkdown:md,onShare:Wn?()=>void lo(Wn,"md-rendered"):void 0}):null,C?h.jsx("div",{"data-testid":"share-toast",role:"status","aria-live":"polite",className:C.kind==="ok"?"fixed left-1/2 top-4 z-50 -translate-x-1/2 rounded-md border border-emerald-500/40 bg-emerald-500/10 px-3 py-2 text-[12px] text-emerald-700 shadow-md dark:text-emerald-300":"fixed left-1/2 top-4 z-50 -translate-x-1/2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-[12px] text-destructive shadow-md",children:C.text}):null]})}function Aue({onConfirm:e,onCancel:t}){return h.jsx("div",{role:"dialog","aria-modal":"true","data-testid":"force-stop-confirm",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40",onClick:t,children:h.jsxs("div",{className:"max-w-sm w-[92%] rounded-lg border border-red-400/40 bg-bg-0 p-4 shadow-xl",onClick:n=>n.stopPropagation(),children:[h.jsxs("div",{className:"flex items-start gap-2 mb-3",children:[h.jsx(Ff,{className:"w-5 h-5 text-red-500 shrink-0 mt-0.5"}),h.jsx("div",{className:"text-[14px] text-text-100",children:"强制停止会话进程?会丢失 initialize / 预热缓存,下一次发送需要重新 spawn。"})]}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{type:"button",onClick:t,className:"h-8 px-3 rounded-md text-[12px] text-text-300 hover:bg-text-100/5 cursor-pointer",children:"取消"}),h.jsx("button",{type:"button","data-testid":"force-stop-confirm-ok",onClick:e,className:"h-8 px-3 rounded-md bg-red-500 text-white text-[12px] font-medium hover:bg-red-600 cursor-pointer",children:"强制停止"})]})]})})}function jue(e){return e.split("/").pop()||e}function Lue({state:e,api:t,onSwitchTab:n,onCloseQuickAsk:r,onCloseMd:i,loadMarkdown:s,quickAskSession:o,onPromoteQuickAsk:a}){if(!GP(e))return null;const l=[];e.quickAsk&&l.push({id:"quick-ask",label:"问一下",title:"问一下",icon:h.jsx(cx,{className:"w-3.5 h-3.5"})});for(const c of e.mds)l.push({id:{kind:"md",relPath:c},label:jue(c),title:c,icon:h.jsx(Ci,{className:"w-3.5 h-3.5"})});return h.jsxs("div",{className:"flex flex-col h-full bg-bg-50/60 border-l border-border-strong",children:[h.jsx(Nu,{delayDuration:200,skipDelayDuration:100,children:h.jsx("div",{className:["flex items-stretch h-9 border-b border-text-100/10 shrink-0 overflow-x-auto","[scrollbar-width:none] [-ms-overflow-style:none]","[&::-webkit-scrollbar]:hidden"].join(" "),role:"tablist",children:l.map(c=>{const u=uY(e.active,c.id),d=c.id==="quick-ask"?"quick-ask":`md:${c.id.relPath}`;return h.jsxs(ed,{children:[h.jsx(td,{asChild:!0,children:h.jsxs("div",{role:"tab","aria-selected":u,"data-tab-title":c.title,onClick:()=>n(c.id),className:["group relative flex items-center gap-2 px-3 h-full cursor-pointer select-none","text-[12px] max-w-[180px] shrink-0 transition-colors duration-100",u?"text-text-100":"text-text-400 hover:text-text-100 hover:bg-text-100/[0.04]"].join(" "),children:[c.icon,h.jsx("span",{className:"truncate",children:c.label}),h.jsx("button",{type:"button","aria-label":`关闭 ${c.label}`,className:["ml-1 rounded p-0.5 shrink-0 transition-opacity","hover:bg-text-100/10",u?"opacity-70 hover:opacity-100":"opacity-0 group-hover:opacity-70"].join(" "),onClick:f=>{f.stopPropagation(),c.id==="quick-ask"?r():i(c.id.relPath)},children:h.jsx(Qr,{className:"w-3 h-3"})}),u?h.jsx("span",{"aria-hidden":"true",className:"absolute left-2 right-2 -bottom-px h-[2px] rounded-full bg-accent"}):null]})}),h.jsx(Hl,{side:"bottom",align:"start",className:"max-w-sm break-all",children:c.title})]},d)})})}),h.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[e.quickAsk&&o?h.jsx("div",{className:"absolute inset-0",style:{display:e.active==="quick-ask"?"block":"none"},children:h.jsx(Rue,{session:o,api:t,...a?{onPromoteQuickAsk:a}:{}})}):null,e.mds.map(c=>{const u=e.active!==null&&e.active!=="quick-ask"&&e.active.relPath===c;return h.jsx("div",{className:"absolute inset-0",style:{display:u?"block":"none"},children:h.jsx(ij,{relPath:c,loadMarkdown:s,showTitleBar:!1})},`md-body:${c}`)})]})]})}function Due(e){const t=e instanceof Error?e.message:String(e);return t.length>200?`${t.slice(0,200)}…`:t}function Oue({state:e,extras:t}){const{api:n,session:r}=t,i=Ni(),[s,o]=g.useState(rY()),[a,l]=g.useState(null),c=r.ownerPersonaId!==ST,u=g.useRef(s);u.current=s;const d=g.useRef(!1),f=g.useCallback(async E=>{const j=u.current.quickAsk;l(null);let P;try{P=await YG(n,r,E)}catch(D){Oe("quick-ask","fork failed",D),d.current||l(Due(D));return}if(!P){d.current||l("这条会话还没准备好(没有可派生的对话记录),稍后再试");return}if(d.current){n.sessionDelete(P.sessionId).catch(()=>{});return}nh(j)&&n.sessionDelete(j.sessionId).catch(()=>{}),o(D=>iY(D,{sessionId:P.sessionId}))},[n,r]),p=g.useCallback(async E=>{const j=u.current.quickAsk,P=(j==null?void 0:j.sessionId)===E;try{await XG(n,{sessionId:E,stillEphemeral:P&&nh(j)})&&o(R=>aY(R))}catch(D){Oe("quick-ask","promote failed",D)}},[n]),m=g.useCallback(E=>{o(j=>sY(j,E))},[]),x=g.useCallback(E=>{o(j=>cY(j,E))},[]),w=g.useCallback(()=>{const E=u.current.quickAsk;nh(E)&&n.sessionDelete(E.sessionId).catch(()=>{}),o(j=>oY(j))},[n]),v=g.useCallback(E=>{o(j=>lY(j,E))},[]);g.useEffect(()=>()=>{d.current=!0;const E=u.current.quickAsk;nh(E)&&n.sessionDelete(E.sessionId).catch(()=>{})},[]);const _=ts("sessions")??[],b=s.quickAsk?_.find(E=>E.sessionId===s.quickAsk.sessionId)??{sessionId:s.quickAsk.sessionId,cwd:r.cwd,tool:r.tool}:null,S=g.useCallback(async E=>{const j=await F_(n,i,r.sessionId,E,60),P=await fetch(j);if(!P.ok)throw new Error(`fetch ${P.status} ${P.statusText}`);return P.text()},[n,i,r.sessionId]),C=h.jsx(wj,{state:e,extras:t,onQuickAskInternal:f,onPreviewMdInternal:m}),{initialSize:k,setSize:N}=nY("chat-panel-right-slot-width",480);return h.jsxs(B_,{orientation:"horizontal",className:"flex-1 flex min-w-0 min-h-0",children:[h.jsx(Yf,{id:"chat",minSize:"400px",children:h.jsxs("div",{className:"relative flex flex-col min-w-0 min-h-0 h-full",children:[C,a?h.jsxs("div",{"data-testid":"quick-ask-error",className:"absolute bottom-24 left-1/2 z-10 -translate-x-1/2 max-w-[90%] rounded-md border border-border bg-bg-200 px-3 py-2 text-[12px] text-text-300 shadow-lg",children:[h.jsxs("span",{className:"mr-2",children:["问一下没能打开:",a]}),h.jsx("button",{type:"button","aria-label":"关闭提示",onClick:()=>l(null),className:"text-text-400 hover:text-text-200 cursor-pointer",children:"✕"})]}):null]})}),GP(s)?h.jsxs(h.Fragment,{children:[h.jsx(FP,{className:"w-1 bg-text-100/10 hover:bg-text-100/25 transition-colors cursor-col-resize"}),h.jsx(Yf,{id:"right-slot",defaultSize:`${k}px`,minSize:"360px",maxSize:"800px",onResize:E=>N(E.inPixels),children:h.jsx(Lue,{state:s,api:n,onSwitchTab:x,onCloseQuickAsk:w,onCloseMd:v,loadMarkdown:S,quickAskSession:b,...c?{onPromoteQuickAsk:p}:{}})})]}):null]})}function Bue({extras:e}){const t=KP(e.session.sessionId,e.focused);return h.jsx(Oue,{state:t,extras:e})}function $ue(e,t,n){const r=e?t.find(s=>s.id===e):void 0;if(r!=null&&r.efforts&&r.efforts.length>0)return{options:r.efforts,defaultValue:r.defaultEffort??""};const i=n.find(s=>s.name==="effort");return{options:(i==null?void 0:i.options)??[],defaultValue:typeof(i==null?void 0:i.default)=="string"?i.default:""}}function zue(e,t,n){var l;if(!t)return((l=(e??[]).find(c=>c.id===""))==null?void 0:l.label)??"未指定";const r=t.toLowerCase(),i=[["opus","Opus"],["fable","Fable"],["sonnet","Sonnet"],["haiku","Haiku"]];for(const[c,u]of i){if(!r.includes(c))continue;const d=r.match(new RegExp(`${c}-(\\d+)(?:-(\\d+))?`));return d?d[2]?`${u} ${d[1]}.${d[2]}`:`${u} ${d[1]}`:u}const s=e??[],o=s.find(c=>c.id===t);if(o)return o.label;const a=s.find(c=>c.id&&t.toLowerCase().includes(c.id.toLowerCase()));return a?a.label:t}function Fue(e,t){var m,x,w,v;const{models:n,modes:r,configSchema:i}=t,s=e.resolvedModel??e.model,o=$ue(s,n,i),a=o.options,l=a.some(_=>_.value===e.effort)?e.effort:o.defaultValue,c=e.effort===""&&e.resolvedEffort?((m=a.find(_=>_.value===e.resolvedEffort))==null?void 0:m.label)??e.resolvedEffort:((x=a.find(_=>_.value===l))==null?void 0:x.label)??null,u=((w=i.find(_=>_.name==="permissionMode"))==null?void 0:w.default)??"",d=r.some(_=>_.id===e.permissionMode)?e.permissionMode:u,p=d===u?null:((v=r.find(_=>_.id===d))==null?void 0:v.label)??null;return{modelLabel:zue(n,s),effortOptions:a,effortValue:l,effortLabel:c,modeValue:d,modeLabel:p,modeTone:p===null?null:d==="bypassPermissions"?"danger":"info"}}function Sj(e){let t;return e.map(n=>{const r=n.group&&n.group!==t?n.group:null;return n.group&&(t=n.group),{...n,groupHeading:r}})}function Hue(e){return e.map(t=>({value:t.id,label:t.label,...t.description?{description:t.description}:{},...t.group?{group:t.group}:{}}))}function Uue({testid:e,list:t,options:n,current:r,onSelect:i}){if(t.loading)return h.jsx(Wr,{disabled:!0,"data-testid":`${e}-loading`,className:"text-[12px] text-text-400",children:"正在读取最新模型…"});if(t.error)return h.jsxs(h.Fragment,{children:[h.jsx("div",{"data-testid":`${e}-error`,className:"px-2 py-1.5 text-[11px] text-warning",children:t.error}),h.jsx(Wr,{"data-testid":`${e}-retry`,className:"text-[12px]",onSelect:o=>{o.preventDefault(),t.load()},children:"重试"})]});const s=n??Hue(t.models);return s.length===0?h.jsx(Wr,{disabled:!0,"data-testid":`${e}-empty`,className:"text-[12px] text-text-400",children:"没有可选模型"}):h.jsx(h.Fragment,{children:Sj(s).map((o,a)=>{const l=o.value===r;return h.jsxs(Qe.Fragment,{children:[o.groupHeading?h.jsxs(h.Fragment,{children:[a>0?h.jsx(hm,{}):null,h.jsx(I_,{"data-testid":`${e}-group`,children:o.groupHeading})]}):null,h.jsxs(Wr,{"data-testid":`${e}-option-${o.value||"default"}`,onSelect:()=>i(o.value),className:"items-start gap-2",children:[h.jsxs("span",{className:"min-w-0 flex-1",children:[h.jsx("span",{className:re("block text-[12px]",l?"font-medium text-text-100":"text-text-300"),children:o.label}),o.description?h.jsx("span",{className:"mt-0.5 block text-[11px] text-text-400",children:o.description}):null]}),l?h.jsx(Zo,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-accent"}):null]})]},o.value||"default")})})}function Wue(e,t={}){return{models:e,loading:!1,error:null,load:()=>{},...t}}const que=e=>e instanceof Error?e.message:String(e);function Vue(e,t){const[n,r]=g.useState({key:e,loading:!1,error:null,data:t}),i=g.useRef(0),s=g.useCallback((a,l)=>{const c=++i.current;r(u=>({key:e,loading:!0,error:null,data:u.key===e?u.data:t})),a().then(u=>{i.current===c&&(l==null||l(u),r({key:e,loading:!1,error:null,data:u}))},u=>{i.current===c&&r(d=>({key:e,loading:!1,error:que(u),data:d.key===e?d.data:t}))})},[e]);return{...n.key===e?n:{loading:!1,error:null,data:t},run:s}}const Kue=[];function Gue(e){const t=Ni(),n=g.useMemo(()=>new Xp(t),[t]),r=as(),{capabilities:i}=Im(e),s=Vue(e??"",null),{run:o}=s,a=g.useCallback(()=>{e&&o(()=>n.capabilitiesGet(e,{refresh:!0}),l=>{l&&r.setData(`capabilities/${e}`,()=>l)})},[n,r,e,o]);return{models:(i==null?void 0:i.models)??Kue,loading:s.loading,error:s.error,load:a}}function Yue({models:e,modelList:t,modes:n=[],configSchema:r=[],model:i,resolvedModel:s,resolvedEffort:o,effort:a,permissionMode:l,onPatch:c}){var w;const u=t??Wue(e??[]),d=u.models,f=Fue({model:i,resolvedModel:s,resolvedEffort:o,effort:a,permissionMode:l},{models:d,modes:n,configSchema:r}),p=s??i,m=d.map(v=>{const _=v.id===""&&s?`${v.description?`${v.description};`:""}当前:${s}`:v.description;return{value:v.id,label:v.label,..._?{description:_}:{},...v.group?{group:v.group}:{}}}),x=n.map(v=>({value:v.id,label:v.label,...v.description?{description:v.description}:{}}));return h.jsxs(uP,{children:[h.jsx(dP,{asChild:!0,children:h.jsxs("button",{type:"button","data-testid":"session-config-chip",title:"Model / reasoning effort / permission mode",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full text-[11px] text-text-400 transition-colors outline-none cursor-pointer hover:bg-text-100/5 hover:text-text-200 data-[state=open]:bg-text-100/5",children:[h.jsx("span",{className:"truncate max-w-[120px]","data-testid":"session-config-chip-model",children:p||f.modelLabel}),f.effortLabel?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"text-text-500",children:"·"}),h.jsx("span",{className:"truncate max-w-[80px]","data-testid":"session-config-chip-effort",children:f.effortLabel})]}):null,f.modeLabel?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"text-text-500",children:"·"}),h.jsx("span",{"data-testid":"session-config-chip-mode","data-tone":f.modeTone,className:re("font-semibold",f.modeTone==="danger"?"text-red-400":"text-blue-400"),children:f.modeLabel})]}):null]})}),h.jsxs(k_,{side:"top",align:"end",className:"w-[230px]","data-testid":"session-config-menu",children:[h.jsx(Xue,{list:u,current:i,currentLabel:f.modelLabel,options:m,onSelect:v=>c({model:v})}),h.jsx(NE,{testid:"session-config-effort",label:"Reasoning effort",current:f.effortValue,currentLabel:f.effortLabel??"—",options:f.effortOptions,onSelect:v=>c({effort:v})}),x.length>0?h.jsx(NE,{testid:"session-config-mode",label:"Permission mode",current:f.modeValue,currentLabel:((w=n.find(v=>v.id===f.modeValue))==null?void 0:w.label)??"—",currentTone:f.modeTone,options:x,onSelect:v=>c({permissionMode:v})}):null]})]})}function kj({label:e,currentLabel:t,currentTone:n}){return h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"flex-1 text-text-200",children:e}),h.jsx("span",{className:re("truncate max-w-[100px]",n==="danger"?"text-red-400 font-semibold":n==="info"?"text-blue-400 font-semibold":"text-text-400"),children:t}),h.jsx(Fn,{className:"w-3.5 h-3.5 shrink-0 text-text-500"})]})}function Xue({list:e,current:t,currentLabel:n,options:r,onSelect:i}){const[s,o]=g.useState(!1),a=l=>{l&&!s&&e.load(),o(l)};return h.jsxs(hP,{open:s,onOpenChange:a,children:[h.jsx(C_,{"data-testid":"session-config-model",className:"gap-2 text-[12px]",children:h.jsx(kj,{label:"Model",currentLabel:n})}),h.jsx(E_,{className:"w-[220px] max-h-[320px] overflow-y-auto",children:h.jsx(Uue,{testid:"session-config-model",list:e,options:r,current:t,onSelect:i})})]})}function NE({testid:e,label:t,current:n,currentLabel:r,currentTone:i,options:s,onSelect:o}){const a=s.length===0;return h.jsxs(hP,{children:[h.jsx(C_,{"data-testid":e,disabled:a,className:"gap-2 text-[12px]",children:h.jsx(kj,{label:t,currentLabel:r,currentTone:i??null})}),h.jsx(E_,{className:"w-[220px] max-h-[320px] overflow-y-auto",children:Sj(s).map((l,c)=>{const u=l.value===n;return h.jsxs(Qe.Fragment,{children:[l.groupHeading?h.jsxs(h.Fragment,{children:[c>0?h.jsx(hm,{}):null,h.jsx(I_,{"data-testid":`${e}-group`,children:l.groupHeading})]}):null,h.jsxs(Wr,{"data-testid":`${e}-option-${l.value||"default"}`,onSelect:()=>o(l.value),className:"items-start gap-2",children:[h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:re("block text-[12px]",u?"text-text-100 font-medium":"text-text-300"),children:l.label}),l.description?h.jsx("span",{className:"block text-[11px] text-text-400 mt-0.5",children:l.description}):null]}),u?h.jsx(Zo,{className:"w-3.5 h-3.5 shrink-0 text-accent mt-0.5"}):null]})]},l.value||"default")})})]})}function Zue(e,t,n=0){const[r,i]=g.useState(null),[s,o]=g.useState(!1),a=g.useCallback(async()=>{if(!t){i(null);return}o(!0);try{const l=await e.getGitBranch(t);i(l.branch??null)}catch{i(null)}finally{o(!1)}},[e,t]);return g.useEffect(()=>{a()},[a,n]),{branch:r,loading:s,refresh:()=>void a()}}function Que(e,t,n=0){const[r,i]=g.useState(null),[s,o]=g.useState(!1),a=g.useCallback(async()=>{if(!t){i(null);return}o(!0);try{const l=await e.getGitRoot(t);i(l.gitRoot??null)}catch{i(null)}finally{o(!1)}},[e,t]);return g.useEffect(()=>{a()},[a,n]),{worktreeRoot:r,loading:s,refresh:()=>void a()}}const Jue=5e3;function ede(e,t,n=0){const[r,i]=g.useState(null);return g.useEffect(()=>{if(!t){i(null);return}let s=!1;const o=async()=>{try{const l=await e.cloudVolumeGet();s||i(l.volume??null)}catch{s||i(null)}},a=n>0?setTimeout(()=>void o(),Jue):null;return a||o(),()=>{s=!0,a&&clearTimeout(a)}},[e,t,n]),{volume:r}}const tde=90;function nde(e){return e.sizeBytes>0?Math.min(100,Math.max(0,Math.round(e.usedBytes/e.sizeBytes*100))):0}function TE(e){const t=e/1073741824;return t>=.1?`${t.toFixed(1)} GB`:`${Math.max(1,Math.round(e/1024**2))} MB`}function rde({volume:e}){if(!e)return null;const t=nde(e),n=t>=tde?"warn":"ok",r=new Date(e.measuredAt).toLocaleString(),i=n==="ok"?"上一次任务结束时量的。":"盘快满了:在会话里说「清理一下云盘」,persona 会分析工作区里哪些能删、列给你确认后清掉。";return h.jsxs("span",{"data-testid":"chat-header-cloud-volume","data-tone":n,title:`云盘已用 ${TE(e.usedBytes)} / ${TE(e.sizeBytes)}(${r})。${i}`,className:re("ml-1.5 inline-flex items-center gap-1.5 px-1.5 py-0.5 rounded text-[11px] tabular-nums",n==="ok"&&"bg-text-100/10 text-text-400",n==="warn"&&"bg-warning-dim text-warning"),children:[h.jsx("span",{className:"relative inline-block w-8 h-1 rounded-full bg-current/20 overflow-hidden","aria-hidden":!0,children:h.jsx("span",{className:"absolute inset-y-0 left-0 rounded-full bg-current",style:{width:`${t}%`}})}),"云盘 ",t,"%"]})}function ide({api:e,session:t,focused:n,totalPanes:r,onFocus:i,onClose:s,onNewSession:o,onOpenConfig:a,onFork:l,onQuickAsk:c,className:u,viewerRole:d="owner",hideHeader:f}){const{capabilities:p}=Im(t.tool),m=Gue(t.tool),[x,w]=g.useState(0),[v,_]=g.useState(n);Qe.useEffect(()=>{n&&_(!0)},[n]);const b=ox(t.tool),S=b?void 0:t.cwd,{branch:C}=Zue(e,S,x),{worktreeRoot:k}=Que(e,S,x),{volume:N}=ede(e,b,x),E=r>1,j=P=>{e.sessionUpdate(t.sessionId,P).catch(D=>{console.error("[session-config] session:update failed",t.sessionId,D)})};return h.jsxs("div",{className:`group/pane relative flex-1 ${u??"flex"} flex-row min-w-0 min-h-0 overflow-hidden ${E?`rounded-md border transition-colors ${n?"border-accent ring-1 ring-accent":"border-border"}`:""}`,onMouseDown:i,"data-testid":`session-pane-${t.sessionId}`,children:[h.jsx(B_,{orientation:"horizontal",className:"flex-1 flex min-w-0 min-h-0",children:h.jsx(Yf,{id:"chat",minSize:"400px",children:h.jsx("div",{className:"flex flex-col min-w-0 min-h-0 h-full",children:(n||v)&&h.jsx(sde,{api:e,session:t,focused:n,liveGitBranch:C,liveWorktreeRoot:k,...b&&N?{cloudVolume:h.jsx(rde,{volume:N})}:{},onNewSession:o,onTurnEnd:()=>w(P=>P+1),onOpenConfig:a,onFork:l,onQuickAsk:c,viewerRole:d,hideHeader:f,configSlot:p?h.jsx(Yue,{modelList:m,modes:p.permissionModes,configSchema:p.configSchema,model:t.model??"",...t.resolvedModel?{resolvedModel:t.resolvedModel}:{},...t.resolvedEffort?{resolvedEffort:t.resolvedEffort}:{},effort:t.effort??"",permissionMode:t.permissionMode??"",onPatch:j}):null})})})}),E&&h.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),s()},className:"absolute top-1.5 right-1.5 z-10 p-1 rounded-md bg-bg-100/80 backdrop-blur-sm border border-border opacity-0 group-hover/pane:opacity-100 transition-opacity text-text-400 hover:text-text-100 hover:bg-bg-200","aria-label":"close pane","data-testid":`session-pane-close-${t.sessionId}`,children:h.jsx(Qr,{className:"w-3.5 h-3.5"})})]})}function sde({api:e,session:t,focused:n,liveGitBranch:r,liveWorktreeRoot:i,cloudVolume:s,onNewSession:o,onTurnEnd:a,onOpenConfig:l,onFork:c,onQuickAsk:u,viewerRole:d,configSlot:f,hideHeader:p}){return h.jsx(Bue,{extras:{session:t,api:e,focused:n,...r!==void 0?{liveGitBranch:r}:{},...i!==void 0?{liveWorktreeRoot:i}:{},...s!==void 0?{cloudVolume:s}:{},onNewSession:o,onTurnEnd:a,onOpenConfig:l,...c?{onFork:m=>{c(m)}}:{},...u?{onQuickAsk:m=>{u(m)}}:{},...d?{viewerRole:d}:{},...f?{configSlot:f}:{},...p?{hideHeader:p}:{}}})}function ode({personas:e,sessions:t,api:n,selfPrincipalId:r,selectedPersonaId:i,selectedSessionId:s,selectedSession:o,onSelectPersona:a,onSelectSession:l,onCreateSession:c,onDeleteSession:u,onEditSession:d,onCloseSession:f}){return h.jsxs("div",{className:"flex h-screen min-h-0 bg-bg-50","data-testid":"guest-share-page",children:[h.jsx("aside",{className:"w-[280px] shrink-0 overflow-y-auto border-r border-border bg-bg-50",children:h.jsx(AK,{personas:e,sessions:t,activePersonaId:i,activeSessionId:s,onSelectPersona:a,onSelectSession:l,onCreateSession:c,onDeleteSession:u,onEditSession:d,showCopyResume:!1,treatSessionsAsRoots:!0,...r?{ownerPrincipalId:r}:{},isPersonaExpanded:()=>!0})}),h.jsx("main",{className:"flex-1 min-w-0 min-h-0 flex",children:o?h.jsx(ide,{api:n,session:o,focused:!0,totalPanes:1,onFocus:()=>{},onClose:f,onNewSession:()=>{},onOpenConfig:()=>{},viewerRole:"guest"}):h.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-xs text-text-400","data-testid":"guest-share-empty",children:"选择左侧 persona 开始对话"})})]})}function ade(){const e=Ni(),t=g.useMemo(()=>new Xp(e),[e]),n=Lz(e),{sessions:r,refresh:i}=Dz(n),{personas:s}=XT(),o=Hz(),a=g.useMemo(()=>{const S=window.location.pathname.match(/^\/s\/([^/]+)/);return S?decodeURIComponent(S[1]):null},[]),l=g.useMemo(()=>r.filter(S=>!S.ephemeral&&S.larkChatId==null),[r]),c=g.useMemo(()=>a?s.filter(S=>S.personaId===a):s,[s,a]),[u,d]=g.useState(null),[f,p]=g.useState(null),[m,x]=g.useState(null);g.useEffect(()=>{let S=!1;return e.request("whoami",{}).then(C=>{S||d(C.capability.id)}).catch(()=>{}),()=>{S=!0}},[e]),g.useEffect(()=>{a&&p(a)},[a]);const w=g.useCallback(async(S,C)=>{const k=await t.sessionCreate({ownerPersonaId:S,...C.trim()?{label:C.trim()}:{}});await i(),p(S),x(k.sessionId)},[t,i]),v=g.useCallback(async S=>{await t.sessionDelete(S),await i(),x(C=>C===S?null:C)},[t,i]),_=g.useCallback(async(S,C)=>{await t.sessionUpdate(S,{label:C.label}),await i()},[t,i]),b=g.useMemo(()=>l.find(S=>S.sessionId===m)??null,[l,m]);return h.jsx(Yy.Provider,{value:o,children:h.jsx(ode,{personas:c,sessions:l,api:t,selfPrincipalId:u,selectedPersonaId:f,selectedSessionId:m,selectedSession:b,onSelectPersona:p,onSelectSession:x,onCreateSession:(S,C)=>void w(S,C),onDeleteSession:S=>void v(S),onEditSession:(S,C)=>void _(S,C),onCloseSession:()=>x(null)})})}const PE="https://app.ttcadvisory.com";function lde({onAuthed:e}){const[t,n]=g.useState(!1),[r,i]=g.useState(null),s=g.useRef(null);g.useEffect(()=>()=>{s.current&&window.removeEventListener("message",s.current)},[]);const o=g.useCallback(()=>{s.current&&(window.removeEventListener("message",s.current),s.current=null),n(!0),i(null);const a=window.location.origin,l=`${PE}/auth/authorize?callback_url=${encodeURIComponent(a)}&auto=1`,c=async d=>{if(d.origin!==PE)return;const f=d.data;if((f==null?void 0:f.type)==="AUTH_CANCEL"){u(),n(!1);return}if(!((f==null?void 0:f.type)!=="AUTH_SUCCESS"||!f.token)){u();try{const p=await fetch(`${window.location.origin}/share/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ttcToken:f.token})});if(!p.ok){const x=await p.json().catch(()=>({}));throw new Error(x.code??`exchange failed (${p.status})`)}const m=await p.json();if(!m.visitorToken)throw new Error("no visitorToken in response");e(m.visitorToken)}catch(p){i(p instanceof Error?p.message:String(p)),n(!1)}}},u=()=>{window.removeEventListener("message",c),s.current=null};s.current=d=>void c(d),window.addEventListener("message",s.current),window.open(l,"ttc-login","width=480,height=640")},[e]);return h.jsx("div",{className:"flex min-h-screen items-center justify-center bg-bg-50 p-6 font-sans text-text-100","data-testid":"guest-login",children:h.jsxs("div",{className:"flex w-full max-w-xs flex-col gap-3 rounded-lg border border-border bg-bg-100 px-5 py-6",children:[h.jsx("h1",{className:"text-base font-semibold",children:"登录后进入分享"}),h.jsx("p",{className:"text-[11px] leading-snug text-text-400",children:"使用飞书账号登录,即可在浏览器里与分享给你的 persona 交互,无需安装。"}),r?h.jsxs("p",{className:"text-[11px] leading-snug text-error","data-testid":"guest-login-error",children:["登录失败:",r]}):null,h.jsx("button",{type:"button",disabled:t,onClick:()=>o(),"data-testid":"guest-login-button",className:"w-full rounded border border-border bg-bg-50 px-2 py-1.5 text-xs text-text-200 transition-colors hover:bg-text-100/5 hover:text-text-100 disabled:opacity-50",children:t?"请在弹窗中完成授权…":"飞书登录"})]})})}const C1="clawd-visitor:token";function cde(e,t){const r=`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}`;return t!=null&&t.devPath?`${r}${t.devPath}`:r}function ude(){return{async getUrl(e){const t=localStorage.getItem(C1);if(!t)throw new Error("NO_VISITOR_TOKEN");const n=cde(window.location,{});return await FT(e).upsert({id:"guest",name:"访客",mode:"remote",url:n,token:t}),{url:n}}}}function dde(e){const t=n=>{document.documentElement.classList.toggle("dark",n==="dark")};return t(e.theme.mode),e.onThemeChange(n=>t(n.mode))}function hde(){const e=Ni(),t=g.useMemo(()=>jz(e),[e]);return h.jsx(mz,{cache:t.cache,children:h.jsx(xz,{children:h.jsx(ade,{})})})}function fde({host:e}){const[t]=g.useState(()=>localStorage.getItem(C1)),[n,r]=g.useState(!1),[i,s]=g.useState(null);return g.useEffect(()=>dde(e),[e]),g.useEffect(()=>{if(!t)return;let o=!1;return ude().getUrl(e).then(()=>{o||r(!0)}).catch(a=>{o||s(a instanceof Error?a.message:String(a))}),()=>{o=!0}},[e,t]),t?h.jsx(Vw,{host:e,children:h.jsx(CS,{children:i?h.jsxs("div",{className:"flex min-h-screen items-center justify-center bg-bg-50 p-6 text-center text-xs text-error","data-testid":"guest-share-connect-error",children:["连接失败:",i]}):n?h.jsx(hz,{host:e,children:h.jsx(hde,{})}):h.jsx("div",{className:"flex min-h-screen items-center justify-center bg-bg-50 p-6 text-xs text-text-400",children:"正在连接…"})})}):h.jsx(Vw,{host:e,children:h.jsx(CS,{children:h.jsx(lde,{onAuthed:o=>{localStorage.setItem(C1,o),window.location.reload()}})})})}function pde({filePath:e,oldString:t,newString:n,content:r}){const i=g.useMemo(()=>r!=null?r.split(/\r?\n/).map(s=>({type:"add",text:s})):mde(t??"",n??""),[t,n,r]);return h.jsxs("div",{"data-testid":"inline-diff",className:"min-w-0 max-w-full rounded-lg border border-bg-300/60 bg-bg-50 overflow-hidden text-[12px] font-mono",children:[h.jsx("div",{className:"flex min-w-0 items-center gap-2 px-3 py-1.5 border-b border-bg-300/40 bg-bg-100/30",children:h.jsx("span",{className:"min-w-0 text-text-400 truncate",title:e,children:e})}),h.jsx("div",{className:"max-h-[320px] max-w-full overflow-auto",children:i.map((s,o)=>h.jsxs("div",{"data-testid":`diff-line-${s.type}`,className:re("flex min-w-max gap-2 px-3 py-0.5 whitespace-pre",s.type==="add"?"bg-success/10 text-success":s.type==="remove"?"bg-error/10 text-error":"text-text-300"),children:[h.jsx("span",{className:"w-3 shrink-0 select-none opacity-60",children:s.type==="add"?"+":s.type==="remove"?"-":" "}),h.jsx("span",{className:"flex-1",children:s.text||" "})]},o))})]})}function mde(e,t){const n=e.split(/\r?\n/),r=t.split(/\r?\n/),i=n.length,s=r.length,o=Array.from({length:i+1},()=>new Array(s+1).fill(0));for(let u=i-1;u>=0;u--)for(let d=s-1;d>=0;d--)o[u][d]=n[u]===r[d]?o[u+1][d+1]+1:Math.max(o[u+1][d],o[u][d+1]);const a=[];let l=0,c=0;for(;l<i&&c<s;)n[l]===r[c]?(a.push({type:"equal",text:n[l]}),l++,c++):o[l+1][c]>=o[l][c+1]?(a.push({type:"remove",text:n[l]}),l++):(a.push({type:"add",text:r[c]}),c++);for(;l<i;)a.push({type:"remove",text:n[l++]});for(;c<s;)a.push({type:"add",text:r[c++]});return a}function gde({items:e}){return e.length===0?null:h.jsxs("div",{"data-testid":"todo-checklist",className:"rounded-lg border border-bg-300/60 bg-bg-50 px-3 py-2 text-[13px]",children:[h.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-text-400/70 mb-1.5",children:"Todos"}),h.jsx("ul",{className:"flex flex-col gap-1",children:e.map((t,n)=>{const r=t.status==="in_progress"&&t.activeForm||t.content;return h.jsxs("li",{"data-testid":`todo-item-${t.status}`,className:"flex items-start gap-2",children:[h.jsx(vde,{status:t.status}),h.jsx("span",{className:re("flex-1 leading-snug",t.status==="completed"?"text-text-400 line-through":t.status==="in_progress"?"text-text-100 font-medium":"text-text-200"),children:r})]},n)})})]})}function vde({status:e}){return e==="completed"?h.jsx(Xy,{className:"w-3.5 h-3.5 text-success mt-0.5 shrink-0"}):e==="in_progress"?h.jsx(Tn,{className:"w-3.5 h-3.5 text-warning mt-0.5 shrink-0 animate-spin"}):h.jsx(_7,{className:"w-3.5 h-3.5 text-text-400 mt-0.5 shrink-0"})}function xde(e){const t=e??{};return Array.isArray(t.todos)?t.todos.map(n=>{if(!n||typeof n!="object")return null;const r=n,i=typeof r.content=="string"?r.content:"",s=r.status==="pending"||r.status==="in_progress"||r.status==="completed"?r.status:"pending",o=typeof r.activeForm=="string"?r.activeForm:void 0;return{content:i,status:s,activeForm:o}}).filter(n=>n!==null):[]}function yde({description:e,prompt:t,subagentType:n}){return h.jsxs("div",{"data-testid":"task-checklist",className:"rounded-lg border border-bg-300/60 bg-bg-50 px-3 py-2 text-[13px]",children:[h.jsxs("div",{className:"flex items-center gap-2 text-text-200 font-medium",children:[h.jsx(Zp,{className:"w-3.5 h-3.5 text-accent shrink-0"}),h.jsx("span",{className:"truncate",children:e||"subagent task"}),n?h.jsx("span",{className:"shrink-0 px-1.5 py-0.5 rounded-md text-[10px] font-mono bg-accent/10 text-accent",children:n}):null]}),t?h.jsx("div",{className:"mt-1 text-[12px] text-text-400 leading-snug line-clamp-3",children:t}):null]})}function _de(e){const t=e??{};return{description:typeof t.description=="string"?t.description:"",prompt:typeof t.prompt=="string"?t.prompt:void 0,subagentType:typeof t.subagent_type=="string"?t.subagent_type:void 0}}const bde={render:({input:e})=>Qe.createElement(gde,{items:xde(e)})},wde={render:({input:e})=>{const{description:t,prompt:n,subagentType:r}=_de(e);return Qe.createElement(yde,{description:t,prompt:n,subagentType:r})}},RE={render:({input:e,output:t,error:n,pending:r,fileScope:i,onShareFile:s,onOpenInTab:o,onPreviewMarkdown:a})=>{const l=kde(e),c=l?Qe.createElement(pde,{filePath:l.filePath,oldString:l.oldString,newString:l.newString,content:l.content}):void 0;return Qe.createElement(vM,{tool:Sde(e),input:e,output:t,error:n,pending:r,expandedBody:c,...i?{fileScope:i}:{},...s?{onShareFile:s}:{},...o?{onOpenInTab:o}:{},...a?{onPreviewMarkdown:a}:{}})}};function Sde(e){const t=e??{};return"content"in t&&t.content!==void 0?"Write":("old_string"in t&&t.old_string!==void 0,"Edit")}function kde(e){const t=e??{},n=typeof t.file_path=="string"?t.file_path:null;if(!n)return null;const r=typeof t.old_string=="string"?t.old_string:void 0,i=typeof t.new_string=="string"?t.new_string:void 0,s=typeof t.content=="string"?t.content:void 0;return r==null&&i==null&&s==null?null:{filePath:n,oldString:r,newString:i,content:s}}for(const e of["claude",r9])$a.register(e,"TodoWrite",bde),$a.register(e,"Task",wde),$a.register(e,"Edit",RE),$a.register(e,"Write",RE);const Cj=document.getElementById("root");if(!Cj)throw new Error("guest-main: #root not found");const Cde=sO({});S0.createRoot(Cj).render(h.jsx(Qe.StrictMode,{children:h.jsx(fde,{host:Cde})}));
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Clawd 分享</title>
7
- <script type="module" crossorigin src="/share-ui/assets/guest-Ddf5o_X4.js"></script>
7
+ <script type="module" crossorigin src="/share-ui/assets/guest-CKWAbuoe.js"></script>
8
8
  <link rel="stylesheet" crossorigin href="/share-ui/assets/guest-4rwUzpVX.css">
9
9
  </head>
10
10
  <body style="margin: 0">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawos-dev/clawd",
3
- "version": "0.2.686",
3
+ "version": "0.2.688",
4
4
  "description": "Standalone clawd daemon — Claude Code (and future Codex) session server over WebSocket",
5
5
  "type": "module",
6
6
  "license": "MIT",