conversationShareContext.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const SHARE_CONTEXT_BLOCK_PATTERN =
  2. /(?:\n\n)?# zcode-share-context:\n```zcode-share-context\n([\s\S]*?)\n```\s*$/u;
  3. interface ConversationShareContextReference {
  4. contextId: string;
  5. shareUrl: string;
  6. }
  7. /**
  8. * 从会话 snapshot 里取出仍可 attach 的 share handover context。
  9. *
  10. * 刻意只吃 snapshot(不接受独立参数):这条线断过一次——composer 原本读一个平行的
  11. * sharedContextImport prop,而 SessionPane 从没传,于是首条消息永远不带 sharedContextRefs,
  12. * CLI 侧 pending→reserved→attached 一步都走不了,模型拿不到分享内容(顶部只读块却照常显示,
  13. * 所以肉眼看不出来)。snapshot 是 composer 必然拿到的东西,从它推导就不可能再漏接。
  14. *
  15. * legacy 形状(只有 title、没有 contextId)返回 null:没有 contextId 就无法构造
  16. * sharedContextRefs,attach 也就无从谈起。
  17. */
  18. export function resolveAttachableShareContext(
  19. sharedContextImport:
  20. | { contextId: string; title: string; shareUrl: string; status: string }
  21. | { title: string }
  22. | null
  23. | undefined,
  24. ): { contextId: string; title: string; shareUrl: string; status: string } | null {
  25. if (!sharedContextImport || !("contextId" in sharedContextImport)) return null;
  26. return sharedContextImport.status === "discarded" ? null : sharedContextImport;
  27. }
  28. function isReference(value: unknown): value is ConversationShareContextReference {
  29. if (!value || typeof value !== "object" || Array.isArray(value)) return false;
  30. const candidate = value as Record<string, unknown>;
  31. if (Object.keys(candidate).some((key) => key !== "contextId" && key !== "shareUrl")) return false;
  32. if (typeof candidate.contextId !== "string" || typeof candidate.shareUrl !== "string")
  33. return false;
  34. try {
  35. const url = new URL(candidate.shareUrl);
  36. return /^\/cn\/share\/[^/]+$/u.test(url.pathname) && !url.search && !url.hash;
  37. } catch {
  38. return false;
  39. }
  40. }
  41. /**
  42. * 从可见正文里剥掉历史消息可能带的 share URL 尾块。
  43. *
  44. * 这个块已经不再产出:它纯粹是 renderer 自产自销(CLI/shared 里没有任何消费者),唯一作用
  45. * 是驱动一个已被裁掉的 chip,代价却是把 share URL 塞进发给模型的正文。写入端已删除,这里
  46. * 只保留读取端,避免「接线修复到 chip 删除」之间发出的消息把裸 markup 当正文显示出来。
  47. */
  48. export function parseConversationShareContext(text: string): {
  49. visibleContent: string;
  50. reference: ConversationShareContextReference | null;
  51. } {
  52. const match = text.match(SHARE_CONTEXT_BLOCK_PATTERN);
  53. if (!match) return { visibleContent: text, reference: null };
  54. try {
  55. const parsed: unknown = JSON.parse(match[1] ?? "");
  56. return isReference(parsed)
  57. ? { visibleContent: text.slice(0, match.index).trimEnd(), reference: parsed }
  58. : { visibleContent: text, reference: null };
  59. } catch {
  60. return { visibleContent: text, reference: null };
  61. }
  62. }