{"slug":"share-session","category":"access","job":"trust","added":"2026-11-08T17:41Z","title":"Share Session","description":"A dialog for making an agent session Private or Public via link, with a warning about what it would expose (like code from a private repository) shown before the choice.","url":"https://ai-patterns.app/patterns/access/share-session","markdown":"https://ai-patterns.app/patterns/access/share-session.md","json":"https://ai-patterns.app/api/patterns/access/share-session","seenIn":[{"team":"Claude","source":"https://code.claude.com/docs/en/claude-code-on-the-web"},{"team":"chatgpt","source":"https://help.openai.com/en/articles/7925741-chatgpt-shared-links-faq"}],"spec":"# Share Session\n\n## Summary\nA small dialog for choosing who can see an agent session: Private (only you) or Public (anyone with the link). Agent sessions carry more than a chat: code from the repositories they worked in, file contents, command output. So the dialog states what going public would expose before the person chooses, not after. The link appears only once it actually works.\n\n## When to use\n- People want to show a session to someone else: a teammate, a reviewer, a public post about how they built something.\n- Sessions can contain material whose sharing rules come from elsewhere (a private repository, an internal workspace, uploaded files).\n- Access is all-or-nothing via a link rather than per-person.\n\n## When not to use\n- Access is granted to named people with roles. Use **Invite Members**.\n- The person wants to share one output (a file, a reply, an artifact), not the whole session. Share that object instead.\n- Sharing is controlled by an admin or policy and the person can't change it. Show the current state as read-only and say who decides.\n\n## Anatomy\n- Title and one-line description of what sharing is for (\"Show your work and how you build with the agent.\").\n- Close button.\n- Visibility options: a radio group of rows, each with an icon, a label and one line saying who can see it. The selected row is filled and has a check.\n- Link row (Public only): the URL and a Copy link button.\n- Policy note: a short line about not sharing personal or third-party content, linking to the usage policy.\n- Exposure warning: a bordered box with a warning icon that names what the session would expose (\"This session comes from a private repository. Sharing it can expose the code to anyone with the link.\").\n\n## Behavior\n- Default to Private. Never make a session public without the person choosing it.\n- Choosing an option saves at once; there's no separate Save. A small spinner replaces the check on that row until it's saved.\n- The link row appears only after Public is saved, so a copied link never points to a private session.\n- Switching back to Private revokes the link for everyone at once; say so in the option description or a toast if links may already be out.\n- The exposure warning is computed from the session (its repositories, uploads, connectors) and shown whenever there's something to warn about, in both states, so the person reads it before choosing Public.\n- Escape, the close button and a click outside close the dialog. Focus starts on the selected option and returns to the Share button on close.\n\n## Content guidelines\n- Describe each option by who can see it: \"Only you have access\", \"Anyone with the link can view\".\n- Make the warning concrete: name the source and the consequence (\"a private repository… expose the code\"), not \"may contain sensitive data\".\n- Keep the policy note to one sentence with a link; the dialog isn't the place for the full policy.\n- Say \"Copy link\", then \"Copied\" for a moment; don't open a separate toast for it.\n\n## Accessibility\n- The dialog has `role=\"dialog\"`, `aria-modal=\"true\"` and is labelled by its title and described by its description; focus is trapped inside it.\n- Options are a `role=\"radiogroup\"` of `role=\"radio\"` items with `aria-checked`, a roving tab stop and arrow-key selection.\n- The Public option is linked to the exposure warning with `aria-describedby`, so the warning is read before choosing it.\n- \"Link copied\" is announced through a polite live region. Motion reduces to fades under `prefers-reduced-motion`.\n\n## Related patterns\n- **Invite Members** — Use it instead to give named people access with roles.\n- **Archived Session** — Use it as well: shared sessions stay readable after they're archived.\n- **Incognito Toggle** — Use it as well to keep a session out of history, and out of sharing, from the start.\n- **AI Disclosure Badge** — Use it on the shared page to mark what the agent wrote.\n","code":"\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { Check, ExternalLink, Link2, ShieldCheck, TriangleAlert, X } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type ShareVisibility = \"private\" | \"public\";\n\nexport interface ShareSessionDialogProps {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  visibility: ShareVisibility;\n  /** Called when the person picks an option. Resolve when it has been saved. */\n  onVisibilityChange: (visibility: ShareVisibility) => Promise<void> | void;\n  /** The link to copy once the session is public. */\n  shareUrl: string;\n  /**\n   * A warning about what going public exposes, in one or two sentences\n   * (\"This session comes from a private repository. Sharing it can expose the\n   * code to anyone with the link.\"). Shown whenever it is set.\n   */\n  exposureWarning?: string;\n  title?: string;\n  description?: string;\n  /** Usage-policy line under the options; pass a node to include a link. */\n  policyNote?: React.ReactNode;\n}\n\nconst OPTIONS: {\n  value: ShareVisibility;\n  label: string;\n  description: string;\n  Icon: typeof ShieldCheck;\n}[] = [\n  { value: \"private\", label: \"Private\", description: \"Only you have access\", Icon: ShieldCheck },\n  { value: \"public\", label: \"Public\", description: \"Anyone with the link can view\", Icon: ExternalLink },\n];\n\nfunction useMounted() {\n  return React.useSyncExternalStore(\n    () => () => {},\n    () => true,\n    () => false,\n  );\n}\n\n/**\n * A small dialog for choosing who can see an agent session: Private or\n * Public via link. A warning about what the session would expose stays in\n * view before the choice is made, and the link appears only once it works.\n */\nexport function ShareSessionDialog({\n  open,\n  onOpenChange,\n  visibility,\n  onVisibilityChange,\n  shareUrl,\n  exposureWarning,\n  title = \"Share session\",\n  description = \"Show your work and how you build with the agent.\",\n  policyNote,\n}: ShareSessionDialogProps) {\n  const mounted = useMounted();\n  const reduce = useReducedMotion();\n  const titleId = React.useId();\n  const descId = React.useId();\n  const warningId = React.useId();\n  const dialogRef = React.useRef<HTMLDivElement>(null);\n  const [saving, setSaving] = React.useState<ShareVisibility | null>(null);\n  const [copied, setCopied] = React.useState(false);\n\n  // Focus the selected option on open; restore focus to the trigger on close.\n  React.useEffect(() => {\n    if (!open) return;\n    const previous = document.activeElement as HTMLElement | null;\n    const id = window.requestAnimationFrame(() => {\n      dialogRef.current?.querySelector<HTMLElement>(\"[role='radio'][aria-checked='true']\")?.focus();\n    });\n    return () => {\n      window.cancelAnimationFrame(id);\n      previous?.focus();\n    };\n  }, [open]);\n\n  React.useEffect(() => {\n    if (!copied) return;\n    const t = window.setTimeout(() => setCopied(false), 1600);\n    return () => window.clearTimeout(t);\n  }, [copied]);\n\n  async function choose(next: ShareVisibility) {\n    if (next === visibility || saving) return;\n    setSaving(next);\n    try {\n      await onVisibilityChange(next);\n    } finally {\n      setSaving(null);\n    }\n  }\n\n  function onKeyDown(e: React.KeyboardEvent) {\n    if (e.key === \"Escape\") {\n      e.stopPropagation();\n      onOpenChange(false);\n      return;\n    }\n    if (e.key === \"Tab\") {\n      // Keep focus inside the dialog.\n      const items = Array.from(\n        dialogRef.current?.querySelectorAll<HTMLElement>(\"button:not([disabled]), a[href], [tabindex='0']\") ?? [],\n      );\n      if (items.length === 0) return;\n      const first = items[0];\n      const last = items[items.length - 1];\n      if (e.shiftKey && document.activeElement === first) {\n        e.preventDefault();\n        last.focus();\n      } else if (!e.shiftKey && document.activeElement === last) {\n        e.preventDefault();\n        first.focus();\n      }\n    }\n  }\n\n  function onRadioKey(e: React.KeyboardEvent, index: number) {\n    if (![\"ArrowDown\", \"ArrowUp\", \"ArrowLeft\", \"ArrowRight\"].includes(e.key)) return;\n    e.preventDefault();\n    const step = e.key === \"ArrowDown\" || e.key === \"ArrowRight\" ? 1 : -1;\n    const next = OPTIONS[(index + step + OPTIONS.length) % OPTIONS.length];\n    choose(next.value);\n    dialogRef.current?.querySelector<HTMLElement>(`[data-value='${next.value}']`)?.focus();\n  }\n\n  if (!mounted) return null;\n\n  return createPortal(\n    <AnimatePresence>\n      {open && (\n        <motion.div\n          key=\"share-session\"\n          className=\"fixed inset-0 z-[100] flex items-center justify-center p-4\"\n          initial={{ opacity: 0 }}\n          animate={{ opacity: 1 }}\n          exit={{ opacity: 0 }}\n          transition={{ duration: 0.15 }}\n        >\n          <div className=\"absolute inset-0 bg-black/40\" aria-hidden onClick={() => onOpenChange(false)} />\n          <motion.div\n            ref={dialogRef}\n            role=\"dialog\"\n            aria-modal=\"true\"\n            aria-labelledby={titleId}\n            aria-describedby={descId}\n            onKeyDown={onKeyDown}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: 8 }}\n            animate={{ opacity: 1, scale: 1, y: 0 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: 8 }}\n            transition={{ duration: 0.18, ease: \"easeOut\" }}\n            className=\"relative w-full max-w-md rounded-2xl bg-popover p-5 text-popover-foreground border\"\n          >\n            <div className=\"flex items-start justify-between gap-4\">\n              <h2 id={titleId} className=\"text-base font-semibold\">\n                {title}\n              </h2>\n              <button\n                type=\"button\"\n                onClick={() => onOpenChange(false)}\n                className=\"-m-1 rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n              >\n                <X className=\"size-4\" aria-hidden />\n                <span className=\"sr-only\">Close</span>\n              </button>\n            </div>\n            <p id={descId} className=\"mt-1.5 text-sm text-muted-foreground\">\n              {description}\n            </p>\n\n            <div role=\"radiogroup\" aria-label=\"Who can see this session\" className=\"mt-4 flex flex-col gap-1\">\n              {OPTIONS.map(({ value, label, description: optionDescription, Icon }, index) => {\n                const selected = visibility === value;\n                const isSaving = saving === value;\n                return (\n                  <button\n                    key={value}\n                    type=\"button\"\n                    role=\"radio\"\n                    data-value={value}\n                    aria-checked={selected}\n                    aria-describedby={value === \"public\" && exposureWarning ? warningId : undefined}\n                    tabIndex={selected ? 0 : -1}\n                    onClick={() => choose(value)}\n                    onKeyDown={(e) => onRadioKey(e, index)}\n                    className={cn(\n                      \"flex items-center gap-3 rounded-xl px-3 py-2.5 text-left transition-colors\",\n                      selected ? \"bg-muted\" : \"hover:bg-muted/50\",\n                    )}\n                  >\n                    <Icon className=\"size-4 shrink-0\" aria-hidden />\n                    <span className=\"min-w-0 flex-1\">\n                      <span className=\"block text-sm\">{label}</span>\n                      <span className=\"block text-xs text-muted-foreground\">{optionDescription}</span>\n                    </span>\n                    <span className=\"flex size-4 shrink-0 items-center justify-center\">\n                      {isSaving ? (\n                        <span className=\"size-3 animate-spin rounded-full border-[1.5px] border-current border-t-transparent text-muted-foreground motion-reduce:animate-none\" />\n                      ) : (\n                        selected && !saving && <Check className=\"size-4 text-sky-600 dark:text-sky-400\" aria-hidden />\n                      )}\n                    </span>\n                  </button>\n                );\n              })}\n            </div>\n\n            <AnimatePresence initial={false}>\n              {visibility === \"public\" && !saving && (\n                <motion.div\n                  key=\"link\"\n                  initial={{ opacity: 0, height: 0 }}\n                  animate={{ opacity: 1, height: \"auto\" }}\n                  exit={{ opacity: 0, height: 0 }}\n                  transition={{ duration: reduce ? 0 : 0.18 }}\n                  className=\"overflow-hidden\"\n                >\n                  <div className=\"mt-3 flex items-center gap-2 rounded-xl px-3 py-2 bg-muted/60\">\n                    <Link2 className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden />\n                    <span className=\"min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground\">{shareUrl}</span>\n                    <button\n                      type=\"button\"\n                      onClick={() => {\n                        navigator.clipboard?.writeText(shareUrl).catch(() => {});\n                        setCopied(true);\n                      }}\n                      className=\"shrink-0 rounded-md px-2 py-1 text-xs font-medium transition-colors hover:bg-accent\"\n                    >\n                      {copied ? \"Copied\" : \"Copy link\"}\n                    </button>\n                  </div>\n                  <span className=\"sr-only\" aria-live=\"polite\">\n                    {copied ? \"Link copied\" : \"\"}\n                  </span>\n                </motion.div>\n              )}\n            </AnimatePresence>\n\n            {policyNote && <p className=\"mt-4 text-xs text-muted-foreground\">{policyNote}</p>}\n\n            {exposureWarning && (\n              <div id={warningId} className=\"mt-4 flex items-start gap-2.5 rounded-xl px-3 py-3 bg-muted/60\">\n                <TriangleAlert className=\"mt-0.5 size-4 shrink-0 text-amber-500\" aria-hidden />\n                <p className=\"text-sm\">{exposureWarning}</p>\n              </div>\n            )}\n          </motion.div>\n        </motion.div>\n      )}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n","dependencies":["lucide-react","motion"],"localImports":["@/lib/utils"]}