mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-21 16:06:54 +00:00
feat: open shared AI sessions in the app (#12486)
* feat: open shared AI sessions in the app and list the ones you opened Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: date opened shares by when the reader opened them, and navigate shared rows by keyboard Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: drop the unreachable Stop sharing on the standalone page and never offer to open a draft-only item Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: show share authors as initials and send signed-out readers of a private share to login Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: list shared sessions after show older and leave a fork session's edits unopenable Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: drop the deployed-item link when a share does not name its edits' workspace Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: block outside images in shared transcripts when rendering instead of with a page policy, so leaving a shared session no longer reloads Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: drop picture sources in shared artifacts and treat a non-member on the in-app shared page as a reader Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: open a fork session's drafts for fork members, say why a shared draft is locked, and add a menu to shared sidebar rows Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: open shared artifacts in a session-style preview panel and add sign-in to the standalone shared page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: block outside images when a shared artifact is printed to PDF and explain locked deployed rows Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep mermaid off in a shared artifact's PDF and lock deployed rows for a public share's non-member reader Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: count shared session opens and removals from the reader's list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: update ee-repo-ref to 9ffb89ad54e2ab508573f8f7779b6471b49dcb9f This commit updates the EE repository reference after PR #992 was merged in windmill-ee-private. Previous ee-repo-ref: 6b1f4121b94920baba7234be2ed3cc9e5678722b New ee-repo-ref: 9ffb89ad54e2ab508573f8f7779b6471b49dcb9f Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
co-authored by
Claude Opus 5.5
windmill-internal-app[bot]
Ruben Fiszel
parent
e24a4309d0
commit
b9dc5f26db
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "INSERT INTO ai_shared_session_opened (share_id, email) VALUES ($1, $2)\n ON CONFLICT (share_id, email) DO UPDATE SET opened_at = now()",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Varchar"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "b43d739234309a9341ddd9b18db229a409ffd8c1f96bb07904333bdb94670b52"
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "DELETE FROM ai_shared_session_opened o\n USING ai_shared_session s\n WHERE o.share_id = s.id AND s.workspace_id = $1 AND o.share_id = $2 AND o.email = $3",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Uuid",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "ce5a5c8798e7b525b8dd10f16c63aaca0b6e002c32d33dd1e6c3b03e5e6b18d7"
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT s.id, s.session_id, s.email, s.name, s.is_public, s.message_count, s.created_by,\n s.shared_at, o.opened_at AS \"opened_at?\"\n FROM ai_shared_session s\n LEFT JOIN ai_shared_session_opened o ON o.share_id = s.id AND o.email = $2\n WHERE s.workspace_id = $1 AND (s.email = $2 OR o.share_id IS NOT NULL)\n ORDER BY COALESCE(o.opened_at, s.shared_at) DESC\n LIMIT $3",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "session_id",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "email",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "name",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "is_public",
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"name": "message_count",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 6,
|
||||
"name": "created_by",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 7,
|
||||
"name": "shared_at",
|
||||
"type_info": "Timestamptz"
|
||||
},
|
||||
{
|
||||
"ordinal": 8,
|
||||
"name": "opened_at?",
|
||||
"type_info": "Timestamptz"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Text",
|
||||
"Int8"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "d492e188a54842b4e7580e6668e894a966bb72705e6b29eeb790bda6b4d64f4e"
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
e4bfe4229dfd07f6c356835c2ac0e80c2729d582
|
||||
9ffb89ad54e2ab508573f8f7779b6471b49dcb9f
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS ai_shared_session_opened;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- The shares a member opened by link, which is what lists them in that member's sidebar.
|
||||
-- Removing one from the list deletes its row; opening the link again brings it back.
|
||||
CREATE TABLE ai_shared_session_opened (
|
||||
share_id UUID NOT NULL REFERENCES ai_shared_session(id) ON DELETE CASCADE,
|
||||
email VARCHAR(255) NOT NULL,
|
||||
opened_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (share_id, email)
|
||||
);
|
||||
|
||||
GRANT ALL ON ai_shared_session_opened TO windmill_admin;
|
||||
GRANT ALL ON ai_shared_session_opened TO windmill_user;
|
||||
|
||||
-- The handlers go through the raw pool and scope every query themselves; this is the backstop
|
||||
-- for a future query that reaches the table through UserDB.
|
||||
ALTER TABLE ai_shared_session_opened ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY admin_policy ON ai_shared_session_opened FOR ALL TO windmill_admin USING (true);
|
||||
@@ -118,3 +118,70 @@ async fn private_share_is_for_members_and_public_share_for_anyone(
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn a_share_is_listed_for_a_member_only_once_they_open_it(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
let authed = format!("http://localhost:{port}/api/w/test-workspace/ai/shared_sessions");
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let share: Value = client
|
||||
.post(format!("{authed}/share"))
|
||||
.header("Authorization", MEMBER)
|
||||
.json(&json!({
|
||||
"session_id": "session-1",
|
||||
"name": "Debugging",
|
||||
"message_count": 1,
|
||||
"snapshot": { "messages": [], "artifacts": [] },
|
||||
}))
|
||||
.send()
|
||||
.await?
|
||||
.json()
|
||||
.await?;
|
||||
let id = share["id"].as_str().unwrap().to_string();
|
||||
|
||||
let listed = |token: &'static str| {
|
||||
let req = client
|
||||
.get(format!("{authed}/list"))
|
||||
.header("Authorization", token);
|
||||
async move { anyhow::Ok(req.send().await?.json::<Vec<Value>>().await?) }
|
||||
};
|
||||
|
||||
let mine = listed(MEMBER).await?;
|
||||
assert_eq!(mine.len(), 1, "the author does not see their own share");
|
||||
assert_eq!(mine[0]["session_id"], "session-1");
|
||||
assert!(
|
||||
listed(OTHER_MEMBER).await?.is_empty(),
|
||||
"a share was listed for a member who never opened its link"
|
||||
);
|
||||
|
||||
let resp = client
|
||||
.get(format!(
|
||||
"http://localhost:{port}/api/w/test-workspace/ai_u/shared_sessions/get/{id}"
|
||||
))
|
||||
.header("Authorization", OTHER_MEMBER)
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let opened = listed(OTHER_MEMBER).await?;
|
||||
assert_eq!(opened.len(), 1, "opening the link did not list the share");
|
||||
assert!(
|
||||
opened[0].get("session_id").is_none(),
|
||||
"the author's session id was sent to a reader"
|
||||
);
|
||||
assert!(opened[0]["opened_at"].is_string());
|
||||
|
||||
let resp = client
|
||||
.delete(format!("{authed}/opened/{id}"))
|
||||
.header("Authorization", OTHER_MEMBER)
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
assert!(listed(OTHER_MEMBER).await?.is_empty());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -15730,6 +15730,41 @@ paths:
|
||||
share:
|
||||
$ref: "#/components/schemas/SharedAiSessionInfo"
|
||||
|
||||
/w/{workspace}/ai/shared_sessions/list:
|
||||
get:
|
||||
summary: list the caller's shared AI sessions
|
||||
description: >
|
||||
The caller's own shares and the ones they opened by link, most recently shared or opened
|
||||
first, without their snapshot. Capped at 500. `session_id` is set on the caller's own
|
||||
shares only, `opened_at` on the others.
|
||||
operationId: listSharedAiSessions
|
||||
tags:
|
||||
- ai
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
responses:
|
||||
"200":
|
||||
description: the shares
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/SharedAiSessionInfo"
|
||||
- type: object
|
||||
properties:
|
||||
mine:
|
||||
type: boolean
|
||||
session_id:
|
||||
type: string
|
||||
opened_at:
|
||||
type: string
|
||||
format: date-time
|
||||
description: when the caller last opened this share by link
|
||||
required:
|
||||
- mine
|
||||
|
||||
/w/{workspace}/ai/shared_sessions/set_public/{id}:
|
||||
post:
|
||||
summary: make a shared AI session public, or reserve it to workspace members
|
||||
@@ -15792,6 +15827,7 @@ paths:
|
||||
required:
|
||||
- snapshot
|
||||
- can_unshare
|
||||
- mine
|
||||
properties:
|
||||
snapshot:
|
||||
type: object
|
||||
@@ -15799,6 +15835,33 @@ paths:
|
||||
can_unshare:
|
||||
type: boolean
|
||||
description: whether the caller authored the share or is a workspace admin
|
||||
mine:
|
||||
type: boolean
|
||||
description: whether the caller authored the share
|
||||
|
||||
/w/{workspace}/ai/shared_sessions/opened/{id}:
|
||||
delete:
|
||||
summary: remove a shared AI session from the caller's list
|
||||
description: >
|
||||
The share stays readable by link; opening it again lists it again.
|
||||
operationId: forgetOpenedAiSession
|
||||
tags:
|
||||
- ai
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
responses:
|
||||
"200":
|
||||
description: removed from the list
|
||||
content:
|
||||
text/plain:
|
||||
schema:
|
||||
type: string
|
||||
|
||||
/w/{workspace}/ai/shared_sessions/delete/{id}:
|
||||
delete:
|
||||
|
||||
@@ -39,6 +39,8 @@ pub fn workspaced_service() -> Router {
|
||||
post(share_session).layer(DefaultBodyLimit::max(SHARE_BODY_LIMIT)),
|
||||
)
|
||||
.route("/status", get(get_share_status))
|
||||
.route("/list", get(list_shared_sessions))
|
||||
.route("/opened/{id}", delete(forget_opened_session))
|
||||
.route("/set_public/{id}", post(set_public))
|
||||
.route("/delete/{id}", delete(unshare_session))
|
||||
}
|
||||
@@ -75,6 +77,8 @@ struct SharedSession {
|
||||
snapshot: Box<RawValue>,
|
||||
/// Whether the caller may stop sharing it: its author, or a workspace admin.
|
||||
can_unshare: bool,
|
||||
/// Whether the caller is its author.
|
||||
mine: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -83,6 +87,19 @@ struct ShareStatus {
|
||||
share: Option<SharedSessionInfo>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct SharedSessionListItem {
|
||||
#[serde(flatten)]
|
||||
info: SharedSessionInfo,
|
||||
mine: bool,
|
||||
/// The author's own session id, which means nothing to anyone else: sent to its author only.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
session_id: Option<String>,
|
||||
/// When the caller last opened someone else's share: what dates it in their list.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opened_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ShareStatusQuery {
|
||||
session_id: String,
|
||||
@@ -230,6 +247,53 @@ async fn get_share_status(
|
||||
Ok(Json(ShareStatus { share }))
|
||||
}
|
||||
|
||||
const LIST_LIMIT: i64 = 500;
|
||||
|
||||
/// The caller's own shares and the ones they opened by link, most recently shared or opened
|
||||
/// first and without their snapshot. A share nobody sent the caller stays out of their list.
|
||||
async fn list_shared_sessions(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
) -> JsonResult<Vec<SharedSessionListItem>> {
|
||||
require_plain_user_token(&authed)?;
|
||||
let rows = sqlx::query!(
|
||||
"SELECT s.id, s.session_id, s.email, s.name, s.is_public, s.message_count, s.created_by,
|
||||
s.shared_at, o.opened_at AS \"opened_at?\"
|
||||
FROM ai_shared_session s
|
||||
LEFT JOIN ai_shared_session_opened o ON o.share_id = s.id AND o.email = $2
|
||||
WHERE s.workspace_id = $1 AND (s.email = $2 OR o.share_id IS NOT NULL)
|
||||
ORDER BY COALESCE(o.opened_at, s.shared_at) DESC
|
||||
LIMIT $3",
|
||||
&w_id,
|
||||
&authed.email,
|
||||
LIST_LIMIT,
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await?;
|
||||
|
||||
Ok(Json(
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let mine = row.email == authed.email;
|
||||
SharedSessionListItem {
|
||||
mine,
|
||||
session_id: mine.then_some(row.session_id),
|
||||
opened_at: if mine { None } else { row.opened_at },
|
||||
info: SharedSessionInfo {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
is_public: row.is_public,
|
||||
message_count: row.message_count,
|
||||
created_by: row.created_by,
|
||||
shared_at: row.shared_at,
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Only the author changes who can open their link; an admin may only take it down.
|
||||
async fn set_public(
|
||||
authed: ApiAuthed,
|
||||
@@ -311,7 +375,27 @@ async fn get_shared_session(
|
||||
_ => return Err(not_found()),
|
||||
};
|
||||
|
||||
let mine = member.is_some_and(|a| row.email == a.email);
|
||||
if let Some(reader) = member.filter(|_| !mine) {
|
||||
// Reading must not depend on the sidebar entry being written.
|
||||
if let Err(e) = sqlx::query!(
|
||||
"INSERT INTO ai_shared_session_opened (share_id, email) VALUES ($1, $2)
|
||||
ON CONFLICT (share_id, email) DO UPDATE SET opened_at = now()",
|
||||
row.id,
|
||||
&reader.email,
|
||||
)
|
||||
.execute(&db)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
"Could not record that {} opened shared session {id}: {e}",
|
||||
reader.email
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(SharedSession {
|
||||
mine,
|
||||
can_unshare: member.is_some_and(|a| row.email == a.email || a.is_admin),
|
||||
snapshot: RawValue::from_string(row.snapshot).map_err(|e| {
|
||||
Error::internal_err(format!("Stored session snapshot is not valid JSON: {e}"))
|
||||
@@ -327,6 +411,26 @@ async fn get_shared_session(
|
||||
}))
|
||||
}
|
||||
|
||||
/// Takes a share out of the caller's list. The share itself stays readable by link.
|
||||
async fn forget_opened_session(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Path((w_id, id)): Path<(String, Uuid)>,
|
||||
) -> Result<String> {
|
||||
require_plain_user_token(&authed)?;
|
||||
sqlx::query!(
|
||||
"DELETE FROM ai_shared_session_opened o
|
||||
USING ai_shared_session s
|
||||
WHERE o.share_id = s.id AND s.workspace_id = $1 AND o.share_id = $2 AND o.email = $3",
|
||||
&w_id,
|
||||
id,
|
||||
&authed.email,
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
Ok("Removed from your shared sessions".to_string())
|
||||
}
|
||||
|
||||
async fn unshare_session(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick"
|
||||
without any identifying data leaving the instance.
|
||||
|
||||
It currently carries 103 registered actions across forty-one features (`access_view`, `ai_session`, `ai_chat`,
|
||||
It currently carries 105 registered actions across forty-one features (`access_view`, `ai_session`, `ai_chat`,
|
||||
`ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`,
|
||||
`flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`,
|
||||
`command_script`, `mcp`, `mcp_workspace`, `mcp_external_client`, `hub_script`, `usage_meter`, `sso_groups_claim`,
|
||||
|
||||
@@ -339,6 +339,32 @@
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
/* Draggable gutter between a session's chat and its preview: a real (layout-occupying)
|
||||
10px-wide grab zone, no overlap tricks that could cover the chat's scrollbar
|
||||
or the preview's edge. Transparent at rest; on hover the app-global
|
||||
`.splitpanes__splitter::after` grabber fades in. Uses a dedicated class, not
|
||||
the shared `.splitter-hidden`, which force-zeroes splitter opacity and would
|
||||
hide that grabber. */
|
||||
.splitpanes--vertical.session-splitter > .splitpanes__splitter {
|
||||
background-color: transparent !important;
|
||||
border: none !important;
|
||||
width: 10px !important;
|
||||
}
|
||||
/* Inset the global hover grabber from the pane's top/bottom edges so the line
|
||||
doesn't run the full height, and round its ends into a pill. */
|
||||
.splitpanes--vertical.session-splitter > .splitpanes__splitter::after {
|
||||
top: 8px !important;
|
||||
bottom: 8px !important;
|
||||
height: auto !important;
|
||||
border-radius: 9999px !important;
|
||||
}
|
||||
/* Collapsed preview: the pane is resized to 0 but stays mounted, so remove
|
||||
the gutter entirely — it would otherwise leave a dead 10px drag zone on the
|
||||
chat's right edge. */
|
||||
.splitpanes--vertical.splitter-off > .splitpanes__splitter {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.monaco-workbench > .notifications-toasts.visible {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
*/
|
||||
import Popover from './meltComponents/Popover.svelte'
|
||||
import Tooltip from './meltComponents/Tooltip.svelte'
|
||||
import { userColorClass, userInitials } from './userInitials'
|
||||
import { Badge } from './common'
|
||||
import Button from './common/button/Button.svelte'
|
||||
import type DiffDrawer from './DiffDrawer.svelte'
|
||||
@@ -86,35 +87,16 @@
|
||||
return [self, ...rest]
|
||||
})
|
||||
|
||||
/** Two-letter initials; `john.doe` → `JD`, `alice` → `AL`, no username → `?`. */
|
||||
function initials(u: DraftUser): string {
|
||||
const name = u.username
|
||||
if (!name) return '?'
|
||||
const parts = name.split(/[._\-\s]+/).filter(Boolean)
|
||||
if (parts.length >= 2) {
|
||||
return (parts[0][0] + parts[1][0]).toUpperCase()
|
||||
}
|
||||
return name.slice(0, 2).toUpperCase()
|
||||
return userInitials(u.username)
|
||||
}
|
||||
|
||||
function fullLabel(u: DraftUser): string {
|
||||
return u.username ?? 'Legacy workspace draft'
|
||||
}
|
||||
|
||||
// Deterministic color per username, same circle across rows.
|
||||
const PALETTE = [
|
||||
'bg-blue-500',
|
||||
'bg-emerald-500',
|
||||
'bg-amber-500',
|
||||
'bg-rose-500',
|
||||
'bg-violet-500',
|
||||
'bg-cyan-500'
|
||||
]
|
||||
function colorFor(u: DraftUser): string {
|
||||
const name = u.username ?? ''
|
||||
let hash = 0
|
||||
for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) >>> 0
|
||||
return PALETTE[hash % PALETTE.length]
|
||||
return userColorClass(u.username)
|
||||
}
|
||||
|
||||
// First 3 circles when ≤3 users; first 2 + "+N" overflow when 4+. Sliced from
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { thinkingPreferences } from './thinkingPreferences.svelte'
|
||||
import CodeDisplay from './script/CodeDisplay.svelte'
|
||||
import LinkRenderer from './LinkRenderer.svelte'
|
||||
import MarkdownImage from './MarkdownImage.svelte'
|
||||
import {
|
||||
extractCandidatePaths,
|
||||
remarkWindmillPaths,
|
||||
@@ -98,11 +99,12 @@
|
||||
})
|
||||
|
||||
const candidatePaths = $derived(extractCandidatePaths(message.content))
|
||||
const reasoningPlugins = [gfmPlugin(), { renderer: { a: LinkRenderer } }]
|
||||
const reasoningPlugins = [gfmPlugin(), { renderer: { a: LinkRenderer, img: MarkdownImage } }]
|
||||
const rendererPlugin = {
|
||||
renderer: {
|
||||
pre: CodeDisplay,
|
||||
a: LinkRenderer
|
||||
a: LinkRenderer,
|
||||
img: MarkdownImage
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<script lang="ts">
|
||||
import { ImageOff } from 'lucide-svelte'
|
||||
import { safeHref } from '$lib/utils/safeHref'
|
||||
import { hasUntrustedImages, isLocalImageSrc } from './untrustedImages'
|
||||
|
||||
type Props = {
|
||||
src?: string
|
||||
alt?: string
|
||||
title?: string
|
||||
width?: string | number
|
||||
height?: string | number
|
||||
}
|
||||
let { src, alt, title, width, height }: Props = $props()
|
||||
|
||||
const untrusted = hasUntrustedImages()
|
||||
const blocked = $derived(untrusted && !isLocalImageSrc(src))
|
||||
const href = $derived(blocked ? safeHref(src, window.location.href) : undefined)
|
||||
const label = $derived(alt || title || src || 'image')
|
||||
</script>
|
||||
|
||||
{#if !blocked}
|
||||
<img {src} {alt} {title} {width} {height} />
|
||||
{:else if href}
|
||||
<a
|
||||
{href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="inline-flex items-center gap-1"
|
||||
title="Image from {href}, not loaded here"
|
||||
>
|
||||
<ImageOff size={12} class="shrink-0" />{label}
|
||||
</a>
|
||||
{:else}
|
||||
<span class="inline-flex items-center gap-1 text-tertiary">
|
||||
<ImageOff size={12} class="shrink-0" />{label}
|
||||
</span>
|
||||
{/if}
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { hasUntrustedImages } from './untrustedImages'
|
||||
|
||||
type Props = { srcSet?: string; srcset?: string; media?: string; type?: string }
|
||||
let { srcSet, srcset, media, type }: Props = $props()
|
||||
|
||||
// A `<picture>` picks the first `<source>` that matches over its `<img>`, so a source left in
|
||||
// untrusted markup would load an outside image past MarkdownImage's check of the `<img>`.
|
||||
const untrusted = hasUntrustedImages()
|
||||
</script>
|
||||
|
||||
{#if !untrusted}
|
||||
<source srcset={srcSet ?? srcset} {media} {type} />
|
||||
{/if}
|
||||
@@ -40,6 +40,7 @@
|
||||
import { gfmPlugin } from 'svelte-exmarkdown/gfm'
|
||||
import CodeDisplay from './script/CodeDisplay.svelte'
|
||||
import LinkRenderer from './LinkRenderer.svelte'
|
||||
import MarkdownImage from './MarkdownImage.svelte'
|
||||
import ToolContentDisplay from './ToolContentDisplay.svelte'
|
||||
import ToolConfirmationFooter from './ToolConfirmationFooter.svelte'
|
||||
import ToolMessageActions from './ToolMessageActions.svelte'
|
||||
@@ -105,7 +106,10 @@
|
||||
)
|
||||
|
||||
// The preview pane's renderers, so a model-written link opens in a new tab either way.
|
||||
const planPlugins = [gfmPlugin(), { renderer: { pre: CodeDisplay, a: LinkRenderer } }]
|
||||
const planPlugins = [
|
||||
gfmPlugin(),
|
||||
{ renderer: { pre: CodeDisplay, a: LinkRenderer, img: MarkdownImage } }
|
||||
]
|
||||
|
||||
const confirmAction = $derived(TOOL_CONFIRM_ACTIONS[message.confirmAction ?? 'confirm'])
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import Markdown from 'svelte-exmarkdown'
|
||||
import SimpleEditor from '$lib/components/SimpleEditor.svelte'
|
||||
import LinkRenderer from '../LinkRenderer.svelte'
|
||||
import MarkdownImage from '../MarkdownImage.svelte'
|
||||
import MarkdownImageSource from '../MarkdownImageSource.svelte'
|
||||
import { artifactPlugins } from './artifactPlugins'
|
||||
import '@fontsource-variable/jetbrains-mono/wght.css'
|
||||
import './artifactDocument.css'
|
||||
@@ -27,7 +29,14 @@
|
||||
// link pill and, when given, its code block sit on top of it.
|
||||
const plugins = $derived([
|
||||
...artifactPlugins,
|
||||
{ renderer: { a: LinkRenderer, ...(pre ? { pre } : {}) } }
|
||||
{
|
||||
renderer: {
|
||||
a: LinkRenderer,
|
||||
img: MarkdownImage,
|
||||
source: MarkdownImageSource,
|
||||
...(pre ? { pre } : {})
|
||||
}
|
||||
}
|
||||
])
|
||||
</script>
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { artifactFilename, artifactMimeType, type ArtifactKind } from './artifactsDB'
|
||||
import { artifactHtmlFile } from './artifactExport'
|
||||
import { printArtifact } from './printArtifact'
|
||||
import { hasUntrustedImages } from '../untrustedImages'
|
||||
|
||||
interface Props {
|
||||
name: string
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
let { name, kind, content, disabled = false, iconOnly = false }: Props = $props()
|
||||
|
||||
const untrustedImages = hasUntrustedImages()
|
||||
|
||||
let copied = $state(false)
|
||||
async function copyRaw() {
|
||||
if (!(await copyToClipboard(content))) return
|
||||
@@ -43,7 +46,9 @@
|
||||
},
|
||||
// Markdown only: an html artifact already downloads as .html, and printing it would run its
|
||||
// scripts in this origin.
|
||||
...(kind === 'md'
|
||||
// No .html for someone else's artifact: the file draws its mermaid here and keeps its
|
||||
// images' outside URLs, which the shared viewer blocks.
|
||||
...(kind === 'md' && !untrustedImages
|
||||
? [
|
||||
{
|
||||
label: 'Download as .html',
|
||||
@@ -55,11 +60,15 @@
|
||||
artifactMimeType('html')
|
||||
),
|
||||
disabled
|
||||
},
|
||||
}
|
||||
]
|
||||
: []),
|
||||
...(kind === 'md'
|
||||
? [
|
||||
{
|
||||
label: 'Download as PDF',
|
||||
icon: FileDown,
|
||||
onClick: () => printArtifact(name, content),
|
||||
onClick: () => printArtifact(name, content, { untrustedImages }),
|
||||
disabled
|
||||
}
|
||||
]
|
||||
|
||||
@@ -2,13 +2,25 @@
|
||||
import Markdown from 'svelte-exmarkdown'
|
||||
import { artifactPlugins } from './artifactPlugins'
|
||||
import ArtifactPrintCodeBlock from './ArtifactPrintCodeBlock.svelte'
|
||||
import MarkdownImage from '../MarkdownImage.svelte'
|
||||
import MarkdownImageSource from '../MarkdownImageSource.svelte'
|
||||
import { setUntrustedImages } from '../untrustedImages'
|
||||
import { untrack } from 'svelte'
|
||||
// These load into the app's page, not the print frame: the frame copies the page's stylesheets.
|
||||
import '@fontsource-variable/jetbrains-mono/wght.css'
|
||||
import './artifactDocument.css'
|
||||
|
||||
let { content }: { content: string } = $props()
|
||||
let { content, untrustedImages = false }: { content: string; untrustedImages?: boolean } =
|
||||
$props()
|
||||
|
||||
const plugins = [...artifactPlugins, { renderer: { pre: ArtifactPrintCodeBlock } }]
|
||||
// Mounted in its own root, so the viewer's context does not reach it: the printing page
|
||||
// passes it on, or a shared artifact's outside images load while the PDF is prepared.
|
||||
if (untrack(() => untrustedImages)) setUntrustedImages()
|
||||
|
||||
const plugins = [
|
||||
...artifactPlugins,
|
||||
{ renderer: { pre: ArtifactPrintCodeBlock, img: MarkdownImage, source: MarkdownImageSource } }
|
||||
]
|
||||
</script>
|
||||
|
||||
<div class="wm-doc">
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
<script lang="ts">
|
||||
import MarkdownCodeBlock from '$lib/components/MarkdownCodeBlock.svelte'
|
||||
import { hasUntrustedImages } from '../untrustedImages'
|
||||
|
||||
// Someone else's artifact keeps mermaid off, as its viewer does: a diagram can fetch images
|
||||
// from other hosts without going through MarkdownImage.
|
||||
const renderMermaid = !hasUntrustedImages()
|
||||
</script>
|
||||
|
||||
<!-- The viewer's code block without the chat context its own renderer needs. Mermaid and display
|
||||
blocks are on as in the viewer: only the session's own artifacts are exported. -->
|
||||
<MarkdownCodeBlock renderMermaid lightMermaid renderDisplay staticDisplay />
|
||||
<!-- The viewer's code block without the chat context its own renderer needs. Display blocks are
|
||||
on as in the viewer. -->
|
||||
<MarkdownCodeBlock {renderMermaid} lightMermaid renderDisplay staticDisplay />
|
||||
|
||||
@@ -18,18 +18,22 @@
|
||||
|
||||
interface Props {
|
||||
artifact: PersistedArtifact
|
||||
store: SessionArtifactsStore
|
||||
/** Absent for a `sharedCopy`, which has no history to read. */
|
||||
store?: SessionArtifactsStore
|
||||
/** Version being viewed, or undefined for the current one. Owned by the caller — it
|
||||
* outlives this component, so the viewer must not keep a copy of its own. */
|
||||
pinned?: number
|
||||
onPin: (version: number | undefined) => void
|
||||
/** A copy read from someone else's shared session. A share keeps only the latest text,
|
||||
* so there is no history to pick from, and sharing it again is the author's call. */
|
||||
sharedCopy?: boolean
|
||||
}
|
||||
|
||||
let { artifact, store, pinned, onPin }: Props = $props()
|
||||
let { artifact, store, pinned, onPin, sharedCopy = false }: Props = $props()
|
||||
|
||||
const latest = $derived(currentVersion(artifact))
|
||||
// Nothing to pick between until a second version exists.
|
||||
const hasHistory = $derived(latest > 1)
|
||||
const hasHistory = $derived(!sharedCopy && !!store && latest > 1)
|
||||
|
||||
let pinnedContent = $state<ArtifactVersion | undefined>(undefined)
|
||||
// A pin that arrives with the tab has nothing honest to show until its snapshot lands: the
|
||||
@@ -58,6 +62,7 @@
|
||||
return
|
||||
}
|
||||
const id = artifact.id
|
||||
if (!store) return
|
||||
void store.getVersion(id, version).then(
|
||||
(snapshot) => {
|
||||
if (pinned !== version || artifact.id !== id) return
|
||||
@@ -132,7 +137,7 @@
|
||||
{badge.label}
|
||||
</span>
|
||||
{/if}
|
||||
{#if hasHistory}
|
||||
{#if hasHistory && store}
|
||||
<!-- The body is blank while restoring, so the chip names the version being fetched:
|
||||
the latest is the one version certainly not on screen. -->
|
||||
<ArtifactVersionPicker
|
||||
@@ -146,14 +151,16 @@
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
<!-- Both export and share `shown`, which is still the current document while a pin is
|
||||
restoring, so both wait for it. -->
|
||||
<ArtifactShareButton
|
||||
artifactId={artifact.id}
|
||||
name={shown.name}
|
||||
kind={artifact.kind}
|
||||
content={shown.content}
|
||||
version={shownVersion ?? latest}
|
||||
disabled={restoringPin}
|
||||
/>
|
||||
{#if !sharedCopy}
|
||||
<ArtifactShareButton
|
||||
artifactId={artifact.id}
|
||||
name={shown.name}
|
||||
kind={artifact.kind}
|
||||
content={shown.content}
|
||||
version={shownVersion ?? latest}
|
||||
disabled={restoringPin}
|
||||
/>
|
||||
{/if}
|
||||
<ArtifactExportButton
|
||||
name={shown.name}
|
||||
kind={artifact.kind}
|
||||
@@ -226,13 +233,19 @@
|
||||
>
|
||||
<ClipboardList size={12} class="shrink-0" />
|
||||
<span class="truncate">
|
||||
This revision is not approved · the plan you approved is v{view.backToPlan}
|
||||
{#if sharedCopy}
|
||||
This revision is not approved · the approved plan is v{view.backToPlan}
|
||||
{:else}
|
||||
This revision is not approved · the plan you approved is v{view.backToPlan}
|
||||
{/if}
|
||||
</span>
|
||||
<div class="ml-auto shrink-0">
|
||||
<Button unifiedSize="xs" variant="default" onClick={() => selectVersion(view.backToPlan)}>
|
||||
View the plan
|
||||
</Button>
|
||||
</div>
|
||||
{#if !sharedCopy}
|
||||
<div class="ml-auto shrink-0">
|
||||
<Button unifiedSize="xs" variant="default" onClick={() => selectVersion(view.backToPlan)}>
|
||||
View the plan
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -10,8 +10,15 @@
|
||||
import { currentVersion, type PersistedArtifact } from './artifactsDB'
|
||||
import { planFirst } from './artifactsState.svelte'
|
||||
|
||||
let {
|
||||
readOnly
|
||||
}: {
|
||||
/** A transcript nobody can change: its own artifacts, opened by the caller, none deleted. */
|
||||
readOnly?: { artifacts: PersistedArtifact[]; open: (artifact: PersistedArtifact) => void }
|
||||
} = $props()
|
||||
|
||||
const aiChatManager = getAiChatManager()
|
||||
const artifacts = $derived(aiChatManager.artifacts.artifacts)
|
||||
const artifacts = $derived(readOnly?.artifacts ?? aiChatManager.artifacts.artifacts)
|
||||
// The plan is what the user comes back to, and in update order it sinks under
|
||||
// everything the approved run then produces.
|
||||
const planCount = $derived(artifacts.filter((a) => a.role === 'plan').length)
|
||||
@@ -33,7 +40,9 @@
|
||||
itemKey={(a) => a.id}
|
||||
rowTitle={(a) => a.name}
|
||||
separatorAfter={(_, index) => index === planCount - 1 && planCount < orderedArtifacts.length}
|
||||
onPick={(a: PersistedArtifact) => aiChatManager.openArtifact?.(a.id, a.name, listOpenTarget(a))}
|
||||
onPick={(a: PersistedArtifact) =>
|
||||
readOnly ? readOnly.open(a) : aiChatManager.openArtifact?.(a.id, a.name, listOpenTarget(a))}
|
||||
actions={readOnly ? undefined : deleteAction}
|
||||
>
|
||||
{#snippet row(a)}
|
||||
{@const Icon = rowIcon(a)}
|
||||
@@ -55,26 +64,30 @@
|
||||
>
|
||||
{badge?.label ?? a.kind}
|
||||
</span>
|
||||
<span
|
||||
class="min-w-[4.5rem] shrink-0 text-right text-2xs font-normal text-hint"
|
||||
title={displayDate(new Date(a.updatedAt))}
|
||||
>
|
||||
{#if currentVersion(a) > 1}<span class="tabular-nums">v{currentVersion(a)}</span> ·{/if}
|
||||
<TimeAgo date={new Date(a.updatedAt).toISOString()} compact />
|
||||
</span>
|
||||
{/snippet}
|
||||
{#snippet actions(a)}
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
destructive
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
title="Delete"
|
||||
startIcon={{ icon: Trash2 }}
|
||||
onClick={() => {
|
||||
aiChatManager.closeArtifact?.(a.id)
|
||||
void aiChatManager.artifacts.remove(a.id)
|
||||
}}
|
||||
/>
|
||||
<!-- A share made before edit times were kept has none. -->
|
||||
{#if a.updatedAt}
|
||||
<span
|
||||
class="min-w-[4.5rem] shrink-0 text-right text-2xs font-normal text-hint"
|
||||
title={displayDate(new Date(a.updatedAt))}
|
||||
>
|
||||
{#if currentVersion(a) > 1}<span class="tabular-nums">v{currentVersion(a)}</span> ·{/if}
|
||||
<TimeAgo date={new Date(a.updatedAt).toISOString()} compact />
|
||||
</span>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</SessionStatusPopover>
|
||||
|
||||
{#snippet deleteAction(a: PersistedArtifact)}
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
destructive
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
title="Delete"
|
||||
startIcon={{ icon: Trash2 }}
|
||||
onClick={() => {
|
||||
aiChatManager.closeArtifact?.(a.id)
|
||||
void aiChatManager.artifacts.remove(a.id)
|
||||
}}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
@@ -15,11 +15,15 @@ import ArtifactPrintBody from './ArtifactPrintBody.svelte'
|
||||
// stack a second print behind the first.
|
||||
let preparing = false
|
||||
|
||||
export async function printArtifact(name: string, content: string): Promise<void> {
|
||||
export async function printArtifact(
|
||||
name: string,
|
||||
content: string,
|
||||
{ untrustedImages = false }: { untrustedImages?: boolean } = {}
|
||||
): Promise<void> {
|
||||
if (preparing) return
|
||||
preparing = true
|
||||
try {
|
||||
await preparePrint(name, content)
|
||||
await preparePrint(name, content, untrustedImages)
|
||||
} finally {
|
||||
preparing = false
|
||||
}
|
||||
@@ -30,7 +34,11 @@ const PAGE_MARGIN_MM = 16
|
||||
// so what it measures holds in print.
|
||||
const PRINT_WIDTH_MM = 210 - 2 * PAGE_MARGIN_MM
|
||||
|
||||
async function preparePrint(name: string, content: string): Promise<void> {
|
||||
async function preparePrint(
|
||||
name: string,
|
||||
content: string,
|
||||
untrustedImages: boolean
|
||||
): Promise<void> {
|
||||
const iframe = document.createElement('iframe')
|
||||
iframe.setAttribute('aria-hidden', 'true')
|
||||
iframe.style.cssText = `position:fixed;right:0;bottom:0;width:${PRINT_WIDTH_MM}mm;height:0;border:0`
|
||||
@@ -77,7 +85,10 @@ async function preparePrint(name: string, content: string): Promise<void> {
|
||||
new Promise((resolve) => setTimeout(resolve, 3000))
|
||||
])
|
||||
|
||||
const component = mount(ArtifactPrintBody, { target: doc.body, props: { content } })
|
||||
const component = mount(ArtifactPrintBody, {
|
||||
target: doc.body,
|
||||
props: { content, untrustedImages }
|
||||
})
|
||||
await tick()
|
||||
await diagramsSettled(doc)
|
||||
await imagesSettled(doc)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { getContext, setContext } from 'svelte'
|
||||
|
||||
const KEY = Symbol('untrusted-images')
|
||||
|
||||
/**
|
||||
* Marks the subtree as showing text another user wrote to whoever opens it (a shared session):
|
||||
* an image in it that points elsewhere would report every reader to that host, so the
|
||||
* markdown renderers draw it as a link instead. Every image the subtree can draw from that
|
||||
* text must go through {@link MarkdownImage}, which is the only thing standing between it and
|
||||
* the reader's browser.
|
||||
*/
|
||||
export function setUntrustedImages() {
|
||||
setContext(KEY, true)
|
||||
}
|
||||
|
||||
export function hasUntrustedImages(): boolean {
|
||||
return getContext<boolean | undefined>(KEY) === true
|
||||
}
|
||||
|
||||
/** Sources that reach no third party: embedded bytes, or the Windmill server itself. */
|
||||
export function isLocalImageSrc(src: string | undefined): boolean {
|
||||
if (!src) return false
|
||||
try {
|
||||
const url = new URL(src, window.location.href)
|
||||
return (
|
||||
url.protocol === 'data:' || url.protocol === 'blob:' || url.origin === window.location.origin
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,13 @@
|
||||
import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte'
|
||||
import { maskKey } from './modifiedItemsMask'
|
||||
import { removeHandEdit, renameHandEdit, sessionHandEdits } from './sessionHandEdits.svelte'
|
||||
import { badgeCounts, badgeOf, buildDeployItems, type DeployItem } from './sessionDeployModel'
|
||||
import {
|
||||
badgeCounts,
|
||||
badgeOf,
|
||||
buildDeployItems,
|
||||
editsToken,
|
||||
type DeployItem
|
||||
} from './sessionDeployModel'
|
||||
import { useExistingMaskKeys } from './sessionDeployModel.svelte'
|
||||
import { previewTargetForDeployKind } from './sessionPreviewTabs.svelte'
|
||||
import { PIPELINE_DRAFT_KIND, pipelineFolderFromBundlePath } from '$lib/pipelinePaths'
|
||||
@@ -246,11 +252,7 @@
|
||||
|
||||
// Drafts are what still needs action, so the token counts only them while any
|
||||
// are pending; once none are left it turns green and counts the deployed.
|
||||
const editsLabel = $derived(
|
||||
dockCounts.draft > 0
|
||||
? `${dockCounts.draft} draft${dockCounts.draft === 1 ? '' : 's'}`
|
||||
: `${dockCounts.deployed} deployed`
|
||||
)
|
||||
const editsLabel = $derived(editsToken(dockCounts).label)
|
||||
let editsOpen = $state(false)
|
||||
|
||||
// Routed on the storage `path` — the edit route's key, which for a draft-only
|
||||
@@ -299,11 +301,7 @@
|
||||
|
||||
// Only draft-vs-deployed drives the color: stale/failed live in the drawer's
|
||||
// deploy model, not here.
|
||||
const editsColorClass = $derived(
|
||||
dockCounts.draft > 0
|
||||
? '!bg-indigo-100 !text-indigo-800 hover:!bg-indigo-200 dark:!bg-indigo-700/40 dark:!text-indigo-100 dark:hover:!bg-indigo-600/40'
|
||||
: '!bg-green-100 !text-green-700 hover:!bg-green-200 dark:!bg-green-700/40 dark:!text-green-100 dark:hover:!bg-green-600/40'
|
||||
)
|
||||
const editsColorClass = $derived(editsToken(dockCounts).class)
|
||||
</script>
|
||||
|
||||
{#if committedId && isUnavailable}
|
||||
|
||||
@@ -24,8 +24,21 @@
|
||||
PencilLine,
|
||||
Plus,
|
||||
Rows3,
|
||||
Trash2
|
||||
Link2,
|
||||
Link2Off,
|
||||
Share2,
|
||||
Trash2,
|
||||
X
|
||||
} from 'lucide-svelte'
|
||||
import {
|
||||
invalidateSharedSessions,
|
||||
SHARED_SESSIONS_FILTER_OPTIONS,
|
||||
useSharedSessionsList,
|
||||
type SharedSessionsFilter
|
||||
} from './sharedSessionsList.svelte'
|
||||
import { logSharedSessionRemove } from './sharedSessionTelemetry'
|
||||
import { sharedSessionAppHref, sharedSessionUrl } from './sessionSharing'
|
||||
import { copyToClipboard } from '$lib/utils'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import { goto } from '$lib/navigation'
|
||||
@@ -66,14 +79,21 @@
|
||||
SIDEBAR_RECENT_MS
|
||||
} from '$lib/components/sidebar/SidebarShowOlder.svelte'
|
||||
import DropdownV2 from '$lib/components/DropdownV2.svelte'
|
||||
import { userStore, userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores'
|
||||
import {
|
||||
superadmin,
|
||||
userStore,
|
||||
userWorkspaces,
|
||||
usersWorkspaceStore,
|
||||
workspaceStore
|
||||
} from '$lib/stores'
|
||||
import { workspaceIsFork } from '$lib/utils/workspaceHierarchy'
|
||||
import { WorkspaceService } from '$lib/gen'
|
||||
import { AiService, WorkspaceService } from '$lib/gen'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { currentWorkspaceRootId, workspaceRootId } from './sessionScope.svelte'
|
||||
import { page } from '$app/state'
|
||||
import { overlayStack } from '$lib/components/common/overlayHost.svelte'
|
||||
import DevWorkspaceBadge from '$lib/components/DevWorkspaceBadge.svelte'
|
||||
import { userColorClass, userInitials } from '$lib/components/userInitials'
|
||||
import {
|
||||
dateBucket,
|
||||
GROUP_BY_OPTIONS,
|
||||
@@ -119,10 +139,19 @@
|
||||
return () => clearInterval(handle)
|
||||
})
|
||||
|
||||
// A share's page is under /sessions too, and shows none of the reader's own sessions.
|
||||
const SHARED_PAGE_PREFIX = '/sessions/shared/'
|
||||
const onSharedPage = $derived(page.url.pathname.startsWith(SHARED_PAGE_PREFIX))
|
||||
const activeSharedId = $derived(
|
||||
onSharedPage
|
||||
? decodeURIComponent(page.url.pathname.slice(SHARED_PAGE_PREFIX.length))
|
||||
: undefined
|
||||
)
|
||||
|
||||
// The row the page is showing: the open session on its page, the draft in Home's
|
||||
// composer on Home. Elsewhere `currentSessionId` lingers but no row is selected.
|
||||
const activeRowId = $derived(
|
||||
page.url.pathname.startsWith('/sessions')
|
||||
page.url.pathname.startsWith('/sessions') && !onSharedPage
|
||||
? sessionState.currentSessionId
|
||||
: page.url.pathname === '/'
|
||||
? homeDraft.id
|
||||
@@ -170,6 +199,65 @@
|
||||
// only when a second family shows up); the others always draw headers.
|
||||
const groupBy = useLocalStorageValue<GroupBy>('windmill_sessions_group_by', 'none', 'string')
|
||||
let listRoot: HTMLDivElement | undefined = $state()
|
||||
let sharedRoot: HTMLDivElement | undefined = $state()
|
||||
|
||||
// Other members' shares, listed after the reader's own sessions; the reader's own shares mark
|
||||
// their session's row instead.
|
||||
const sharedFilter = useLocalStorageValue<SharedSessionsFilter>(
|
||||
'windmill_sessions_shared_filter',
|
||||
'show',
|
||||
'string'
|
||||
)
|
||||
const sharedWorkspace = $derived($currentWorkspaceRootId ?? $workspaceStore ?? '')
|
||||
const sharedList = useSharedSessionsList(() => sharedWorkspace || undefined)
|
||||
type SharedRow = (typeof sharedList.items)[number]
|
||||
let pendingUnshare: SharedRow | undefined = $state(undefined)
|
||||
|
||||
async function leaveSharedPage(id: string) {
|
||||
if (id === activeSharedId) await goto('/')
|
||||
}
|
||||
|
||||
async function forgetShared(shared: SharedRow) {
|
||||
try {
|
||||
await AiService.forgetOpenedAiSession({ workspace: sharedWorkspace, id: shared.id })
|
||||
invalidateSharedSessions(sharedWorkspace)
|
||||
logSharedSessionRemove('sidebar', sharedWorkspace)
|
||||
sendUserToast('Removed from your shared sessions')
|
||||
await leaveSharedPage(shared.id)
|
||||
} catch (err) {
|
||||
sendUserToast(`Could not remove it: ${(err as { body?: unknown })?.body ?? err}`, true)
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmUnshare() {
|
||||
const shared = pendingUnshare
|
||||
pendingUnshare = undefined
|
||||
if (!shared) return
|
||||
try {
|
||||
await AiService.unshareAiSession({ workspace: sharedWorkspace, id: shared.id })
|
||||
invalidateSharedSessions(sharedWorkspace)
|
||||
sendUserToast('Stopped sharing: the link no longer opens')
|
||||
await leaveSharedPage(shared.id)
|
||||
} catch (err) {
|
||||
sendUserToast(`Could not stop sharing: ${(err as { body?: unknown })?.body ?? err}`, true)
|
||||
}
|
||||
}
|
||||
const mySharedSessionIds = $derived(
|
||||
new Set(sharedList.items.flatMap((s) => (s.mine && s.session_id ? [s.session_id] : [])))
|
||||
)
|
||||
const sharedWithMe = $derived(
|
||||
sharedFilter.val === 'hide'
|
||||
? []
|
||||
: sharedList.items.filter((s) => {
|
||||
if (s.mine) return false
|
||||
if (s.id === activeSharedId) return true
|
||||
if (lastActivityDays.val === 0) return true
|
||||
return (
|
||||
Date.parse(s.opened_at ?? s.shared_at) >=
|
||||
clock - lastActivityDays.val * 24 * 60 * 60 * 1000
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
// A session's family root: the stored grouping id, else derived live.
|
||||
function sessionRootOf(s: Session): string | undefined {
|
||||
@@ -190,6 +278,7 @@
|
||||
// The row on screen always stays in the list, ignoring every filter.
|
||||
if (s.id === activeRowId) return true
|
||||
if (s.archived && !showArchived.val) return false
|
||||
if (sharedFilter.val === 'only' && !mySharedSessionIds.has(s.id)) return false
|
||||
if (lastActivityDays.val > 0) {
|
||||
const cutoff = clock - lastActivityDays.val * 24 * 60 * 60 * 1000
|
||||
if (sessionLastActivityAt(s) < cutoff) return false
|
||||
@@ -587,6 +676,17 @@
|
||||
action: () => (lastActivityDays.val = o.days)
|
||||
}))
|
||||
},
|
||||
{
|
||||
displayName: 'Shared sessions',
|
||||
icon: Share2,
|
||||
extra: sharedFilterHint,
|
||||
submenuItems: SHARED_SESSIONS_FILTER_OPTIONS.map((o) => ({
|
||||
displayName: o.label,
|
||||
selected: sharedFilter.val === o.value,
|
||||
keepOpen: inFlyout,
|
||||
action: () => (sharedFilter.val = o.value)
|
||||
}))
|
||||
},
|
||||
{
|
||||
displayName: 'Group by',
|
||||
icon: Rows3,
|
||||
@@ -735,10 +835,16 @@
|
||||
})
|
||||
}
|
||||
|
||||
// One sequence across the reader's own sessions and the shared ones below "Show older". Shared
|
||||
// rows are links, the reader's own sessions buttons: both are rows.
|
||||
function sessionRows(): HTMLElement[] {
|
||||
return [listRoot, sharedRoot].flatMap((root) =>
|
||||
root ? Array.from(root.querySelectorAll<HTMLElement>('[data-session-button]')) : []
|
||||
)
|
||||
}
|
||||
|
||||
function focusAt(index: number) {
|
||||
const buttons = listRoot
|
||||
? Array.from(listRoot.querySelectorAll<HTMLButtonElement>('button[data-session-button]'))
|
||||
: []
|
||||
const buttons = sessionRows()
|
||||
if (buttons.length === 0) return
|
||||
const wrapped = ((index % buttons.length) + buttons.length) % buttons.length
|
||||
buttons[wrapped]?.focus()
|
||||
@@ -748,11 +854,9 @@
|
||||
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Home' && e.key !== 'End') {
|
||||
return
|
||||
}
|
||||
const buttons = listRoot
|
||||
? Array.from(listRoot.querySelectorAll<HTMLButtonElement>('button[data-session-button]'))
|
||||
: []
|
||||
const buttons = sessionRows()
|
||||
if (buttons.length === 0) return
|
||||
const current = buttons.indexOf(document.activeElement as HTMLButtonElement)
|
||||
const current = buttons.indexOf(document.activeElement as HTMLElement)
|
||||
e.preventDefault()
|
||||
if (e.key === 'ArrowDown') focusAt(current < 0 ? 0 : current + 1)
|
||||
else if (e.key === 'ArrowUp') focusAt(current < 0 ? buttons.length - 1 : current - 1)
|
||||
@@ -999,8 +1103,11 @@
|
||||
<span class={rail ? 'sr-only' : 'truncate flex-1'}
|
||||
>{session.summary ?? 'Untitled session'}</span
|
||||
>
|
||||
{#if !rail && (draft || unread > 0)}
|
||||
{#if !rail && (draft || unread > 0 || mySharedSessionIds.has(session.id))}
|
||||
<span class="shrink-0 inline-flex items-center gap-1">
|
||||
{#if mySharedSessionIds.has(session.id)}
|
||||
<Link2 class="w-3 h-3 text-tertiary" aria-label="Shared by link" />
|
||||
{/if}
|
||||
{#if draft}
|
||||
<PencilLine class="w-3 h-3 text-tertiary" aria-label="Unsent draft" />
|
||||
{/if}
|
||||
@@ -1211,6 +1318,107 @@
|
||||
{rail}
|
||||
/>
|
||||
{/if}
|
||||
<!-- After "Show older", which belongs to the reader's own sessions above. -->
|
||||
{#if !workspaceTree && sharedWithMe.length > 0 && !selecting}
|
||||
<div
|
||||
bind:this={sharedRoot}
|
||||
class="flex flex-col gap-0.5"
|
||||
onkeydown={handleListKeydown}
|
||||
role="listbox"
|
||||
aria-label="Shared with you"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div
|
||||
class={twMerge(
|
||||
'flex flex-row items-center pl-2 pr-0.5 pt-2 pb-1 min-w-0',
|
||||
displayGroups.length > 0 ? 'mt-4' : '',
|
||||
rail ? 'invisible' : ''
|
||||
)}
|
||||
>
|
||||
<span class="text-secondary text-3xs truncate min-w-0">Shared with you</span>
|
||||
</div>
|
||||
{#each sharedWithMe as shared (shared.id)}
|
||||
{@const isActive = shared.id === activeSharedId}
|
||||
<div
|
||||
class={twMerge(
|
||||
'flex flex-row items-center group rounded min-w-0',
|
||||
isActive ? sidebarClasses.selectedBg : 'hover:bg-surface-hover'
|
||||
)}
|
||||
>
|
||||
<a
|
||||
href={sharedSessionAppHref(sharedWorkspace, shared.id)}
|
||||
data-session-button
|
||||
role="option"
|
||||
aria-selected={isActive}
|
||||
title={rail ? shared.name : `Shared by ${shared.created_by}`}
|
||||
class={twMerge(
|
||||
'flex flex-1 flex-row items-center gap-2 rounded text-left text-xs font-normal focus:outline-none min-w-0 px-2 h-6',
|
||||
isActive ? sidebarClasses.selectedText : 'text-secondary',
|
||||
displayGroups.some((g) => g.showHeader) ? 'pl-3' : ''
|
||||
)}
|
||||
>
|
||||
<Share2 class="w-3 h-3 shrink-0 text-tertiary" aria-hidden="true" />
|
||||
<span class={rail ? 'sr-only' : 'truncate flex-1'}>{shared.name}</span>
|
||||
{#if !rail}
|
||||
<span
|
||||
class="inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[8px] font-semibold text-white {userColorClass(
|
||||
shared.created_by
|
||||
)}"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{userInitials(shared.created_by)}
|
||||
</span>
|
||||
{/if}
|
||||
</a>
|
||||
<div
|
||||
class={twMerge(
|
||||
'transition-opacity pr-0.5',
|
||||
rail ? 'hidden' : 'opacity-0 group-hover:opacity-100 focus-within:opacity-100'
|
||||
)}
|
||||
>
|
||||
<DropdownV2
|
||||
fixedHeight={false}
|
||||
placement="bottom-end"
|
||||
enableFlyTransition
|
||||
items={[
|
||||
{
|
||||
displayName: 'Copy link',
|
||||
icon: Link2,
|
||||
action: () => void copyToClipboard(sharedSessionUrl(sharedWorkspace, shared.id))
|
||||
},
|
||||
{
|
||||
displayName: 'Remove from my list',
|
||||
icon: X,
|
||||
action: () => void forgetShared(shared)
|
||||
},
|
||||
// The server decides; offering it only to admins keeps it off the
|
||||
// menu of a reader it would refuse.
|
||||
...($userStore?.is_admin || $superadmin
|
||||
? [
|
||||
{
|
||||
displayName: 'Stop sharing',
|
||||
icon: Link2Off,
|
||||
type: 'delete' as const,
|
||||
action: () => (pendingUnshare = shared)
|
||||
}
|
||||
]
|
||||
: [])
|
||||
]}
|
||||
>
|
||||
{#snippet buttonReplacement()}
|
||||
<span
|
||||
class="inline-flex items-center justify-center w-5 h-5 rounded text-tertiary hover:bg-surface-hover hover:text-primary"
|
||||
title="More"
|
||||
>
|
||||
<EllipsisVertical size={14} />
|
||||
</span>
|
||||
{/snippet}
|
||||
</DropdownV2>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{#if selecting}
|
||||
<!-- Pinned to the bottom edge of whatever scrolls the list, the sidebar or the folded
|
||||
section's menu, while the rows scroll under it; z-10 keeps it above the sidebar's
|
||||
@@ -1302,6 +1510,20 @@
|
||||
</div>
|
||||
</ConfirmationModal>
|
||||
|
||||
<ConfirmationModal
|
||||
open={!!pendingUnshare}
|
||||
title="Stop sharing"
|
||||
confirmationText="Stop sharing"
|
||||
onConfirmed={confirmUnshare}
|
||||
onCanceled={() => (pendingUnshare = undefined)}
|
||||
>
|
||||
<p>
|
||||
Take down <span class="font-medium text-primary">{pendingUnshare?.name}</span>, shared by
|
||||
{pendingUnshare?.created_by}? The link stops opening for everyone, and only its author can share
|
||||
it again.
|
||||
</p>
|
||||
</ConfirmationModal>
|
||||
|
||||
<ConfirmationModal
|
||||
open={batchDeleteOpen}
|
||||
title="Delete sessions"
|
||||
@@ -1338,6 +1560,12 @@
|
||||
{LAST_ACTIVITY_OPTIONS.find((o) => o.days === lastActivityDays.val)?.hint ?? ''}
|
||||
</span>
|
||||
{/snippet}
|
||||
{#snippet sharedFilterHint()}
|
||||
<span class="text-2xs text-tertiary">
|
||||
{SHARED_SESSIONS_FILTER_OPTIONS.find((o) => o.value === sharedFilter.val)?.hint ?? ''}
|
||||
</span>
|
||||
{/snippet}
|
||||
|
||||
{#snippet groupByHint()}
|
||||
<span class="text-2xs text-tertiary whitespace-nowrap">
|
||||
{GROUP_BY_OPTIONS.find((o) => o.value === groupBy.val)?.hint ?? ''}
|
||||
|
||||
@@ -11,7 +11,11 @@
|
||||
import { copyToClipboard, displayDate } from '$lib/utils'
|
||||
import { shareWorkspaceId } from '$lib/components/copilot/chat/artifacts/artifactSharing'
|
||||
import type { AIChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte'
|
||||
import { buildSessionSnapshot, sharedSessionUrl } from './sessionSharing'
|
||||
import { buildSessionSnapshot, sharedSessionUrl, type SharedSessionEdit } from './sessionSharing'
|
||||
import { badgeOf } from './sessionDeployModel'
|
||||
import { readDeployItems } from './sessionDeployModel.svelte'
|
||||
import { sessionHandEdits } from './sessionHandEdits.svelte'
|
||||
import { invalidateSharedSessions } from './sharedSessionsList.svelte'
|
||||
|
||||
interface Props {
|
||||
sessionId: string
|
||||
@@ -59,6 +63,38 @@
|
||||
|
||||
function reflect(next: SharedAiSessionInfo | undefined) {
|
||||
if (status.current) status.mutate({ ...status.current, share: next })
|
||||
invalidateSharedSessions(workspace)
|
||||
}
|
||||
|
||||
// No mask means the chat never tracked its edits, and listing every draft of the workspace
|
||||
// would share more than this session did.
|
||||
async function readEdits(): Promise<
|
||||
{ workspace: string; items: SharedSessionEdit[] } | undefined
|
||||
> {
|
||||
const chatMask = manager.modifiedItems
|
||||
if (!workspaceId || !chatMask) return undefined
|
||||
const mask = new Set([...chatMask, ...sessionHandEdits(sessionId)])
|
||||
if (mask.size === 0) return undefined
|
||||
try {
|
||||
const items = await readDeployItems(workspaceId, mask)
|
||||
return {
|
||||
// A fork session's share lands in its parent: the fork is named so that a reader
|
||||
// who is also a member of it can open the edits there.
|
||||
workspace: workspaceId,
|
||||
items: items.map((i) => ({
|
||||
kind: i.deployKind,
|
||||
path: i.displayPath,
|
||||
draft: badgeOf(i) === 'draft',
|
||||
draftKind: i.draftKind,
|
||||
draftPath: i.path,
|
||||
draftOnly: i.draftOnly
|
||||
}))
|
||||
}
|
||||
} catch (err) {
|
||||
// The transcript is what the link is for: share it without the edits.
|
||||
console.error('Could not list the session edits to share', err)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function shareSnapshot() {
|
||||
@@ -68,7 +104,8 @@
|
||||
try {
|
||||
const snapshot = buildSessionSnapshot(
|
||||
$state.snapshot(manager.displayMessages),
|
||||
$state.snapshot(manager.artifacts.artifacts)
|
||||
$state.snapshot(manager.artifacts.artifacts),
|
||||
await readEdits()
|
||||
)
|
||||
const shared = await AiService.shareAiSession({
|
||||
workspace,
|
||||
@@ -80,7 +117,10 @@
|
||||
}
|
||||
})
|
||||
if (status.current) reflect(shared)
|
||||
else await status.refetch()
|
||||
else {
|
||||
await status.refetch()
|
||||
invalidateSharedSessions(workspace)
|
||||
}
|
||||
if (updating) {
|
||||
sendUserToast('The link now shows the latest messages')
|
||||
} else if (await copyToClipboard(sharedSessionUrl(workspace, shared.id), false)) {
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
onPick,
|
||||
itemHref,
|
||||
rowTitle,
|
||||
itemDisabled,
|
||||
row,
|
||||
actions,
|
||||
footer,
|
||||
@@ -42,6 +43,9 @@
|
||||
* doing; on a plain click `onPick` may `preventDefault()` to open it in place instead. */
|
||||
itemHref?: (item: T) => string | undefined
|
||||
rowTitle?: (item: T) => string
|
||||
/** A row that does nothing when picked: drawn dimmed, without hover, and ignored on click.
|
||||
* It stays focusable so arrow keys still reach it and its `rowTitle` can say why. */
|
||||
itemDisabled?: (item: T) => boolean
|
||||
/** Content of the row's primary button. */
|
||||
row: Snippet<[T]>
|
||||
/** Trailing per-row action buttons (outside the primary button). */
|
||||
@@ -130,9 +134,12 @@
|
||||
<div class="flex min-h-0 flex-col" bind:this={listRoot} onkeydown={handleListKeydown}>
|
||||
<div role="list" class="{maxHeightClass} overflow-y-auto py-1">
|
||||
{#each items as item, index (itemKey(item))}
|
||||
{@const href = itemHref?.(item)}
|
||||
{@const disabled = itemDisabled?.(item) ?? false}
|
||||
{@const href = disabled ? undefined : itemHref?.(item)}
|
||||
<div
|
||||
class="flex items-center gap-2 py-1 pl-3 pr-2 hover:bg-surface-hover focus-within:bg-surface-hover"
|
||||
class="flex items-center gap-2 py-1 pl-3 pr-2 {disabled
|
||||
? 'opacity-60 has-[:focus-visible]:bg-surface-hover'
|
||||
: 'hover:bg-surface-hover focus-within:bg-surface-hover'}"
|
||||
role="listitem"
|
||||
>
|
||||
<svelte:element
|
||||
@@ -143,9 +150,13 @@
|
||||
target={href ? '_blank' : undefined}
|
||||
rel={href ? 'noopener' : undefined}
|
||||
data-status-row
|
||||
class="flex min-w-0 flex-1 items-center gap-2 text-left font-normal focus:outline-none text-[color:inherit]"
|
||||
aria-disabled={disabled || undefined}
|
||||
class="flex min-w-0 flex-1 items-center gap-2 text-left font-normal focus:outline-none text-[color:inherit] {disabled
|
||||
? 'cursor-default'
|
||||
: ''}"
|
||||
title={rowTitle?.(item)}
|
||||
onclick={(e: MouseEvent) => {
|
||||
if (disabled) return
|
||||
if (href && isNewTabClick(e)) return
|
||||
pick(item, e)
|
||||
}}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
<script lang="ts">
|
||||
import { Link2Off, Loader2, Lock, MessagesSquare } from 'lucide-svelte'
|
||||
import { EmptyState } from '$lib/components/common'
|
||||
import { UserService } from '$lib/gen'
|
||||
import { resource } from 'runed'
|
||||
import { displayDate } from '$lib/utils'
|
||||
import type { Snippet } from 'svelte'
|
||||
import SharedSessionTranscript from './SharedSessionTranscript.svelte'
|
||||
import type { LoadedSharedSession } from './sharedSession.svelte'
|
||||
|
||||
interface Props {
|
||||
loaded: LoadedSharedSession | undefined
|
||||
workspace: string
|
||||
/** The reader is signed in to the workspace, so the author's drafts may open for them. */
|
||||
member?: boolean
|
||||
/** Set when the reader has no session: signing in as a member opens the drafts. */
|
||||
signInHref?: string
|
||||
/** See SharedSessionTranscript. */
|
||||
previewActions?: Snippet
|
||||
}
|
||||
|
||||
let { loaded, workspace, member = false, signInHref, previewActions }: Props = $props()
|
||||
|
||||
const editsWorkspace = $derived(
|
||||
loaded?.state === 'found' ? loaded.snapshot.editsWorkspace : undefined
|
||||
)
|
||||
// A fork session's edits live in the fork while the share lives in its parent, so being a
|
||||
// member of the share's workspace says nothing about reaching them: the fork is asked.
|
||||
const forkMember = resource(
|
||||
() => (editsWorkspace && editsWorkspace !== workspace ? editsWorkspace : undefined),
|
||||
(fork) =>
|
||||
fork
|
||||
? UserService.whoami({ workspace: fork }).then(
|
||||
() => true,
|
||||
() => false
|
||||
)
|
||||
: Promise.resolve(false)
|
||||
)
|
||||
const inFork = $derived(!!editsWorkspace && editsWorkspace !== workspace)
|
||||
// A deployed item opens only inside its workspace, so a public share's non-member reader gets
|
||||
// it listed but locked, as for drafts.
|
||||
const opensEdits = $derived(inFork ? forkMember.current === true : member)
|
||||
const readsDrafts = $derived(inFork ? forkMember.current === true : member)
|
||||
const draftsLockedReason = $derived.by(() => {
|
||||
if (signInHref)
|
||||
return `You are signed out, and only members of ${editsWorkspace ?? workspace} can open the author's edits.`
|
||||
if (inFork) {
|
||||
return forkMember.current === false
|
||||
? `Edited in the fork ${editsWorkspace}, which you are not a member of: only its members can open the author's edits.`
|
||||
: undefined
|
||||
}
|
||||
return member ? undefined : `Only members of ${workspace} can open the author's edits.`
|
||||
})
|
||||
</script>
|
||||
|
||||
{#snippet sharedBy()}
|
||||
{#if loaded?.state === 'found'}
|
||||
<div class="pt-2 text-center text-xs text-secondary">
|
||||
Read-only {loaded.session.is_public ? 'public ' : ''}copy shared by {loaded.session
|
||||
.created_by}
|
||||
· {displayDate(loaded.session.shared_at)}
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#if loaded?.state === 'found' && loaded.snapshot.messages.length > 0}
|
||||
{#key loaded.session.id}
|
||||
<SharedSessionTranscript
|
||||
snapshot={loaded.snapshot}
|
||||
{workspace}
|
||||
author={loaded.session.created_by}
|
||||
editsWorkspace={opensEdits ? editsWorkspace : undefined}
|
||||
{readsDrafts}
|
||||
{draftsLockedReason}
|
||||
draftsSignInHref={signInHref}
|
||||
footer={sharedBy}
|
||||
{previewActions}
|
||||
/>
|
||||
{/key}
|
||||
{:else}
|
||||
<div class="h-full overflow-y-auto">
|
||||
<div class="mx-auto flex min-h-full w-full max-w-3xl flex-col px-7 pt-4">
|
||||
{@render placeholder()}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#snippet placeholder()}
|
||||
{#if loaded?.state === 'found'}
|
||||
<EmptyState icon={MessagesSquare} title="This session has no messages" />
|
||||
{@render sharedBy()}
|
||||
{:else if loaded?.state === 'gone'}
|
||||
<EmptyState
|
||||
icon={Link2Off}
|
||||
title="This shared session is not available"
|
||||
description="Its author stopped sharing it, or the link is incomplete."
|
||||
/>
|
||||
{:else if loaded?.state === 'outsider'}
|
||||
<EmptyState
|
||||
icon={Lock}
|
||||
title="Only members of {workspace} can open this link"
|
||||
description="You are signed in as {loaded.email}, who is not a member of {workspace}. Ask an admin of {workspace} to add you, or ask the author for a public link."
|
||||
/>
|
||||
{:else if loaded?.state === 'error'}
|
||||
<EmptyState
|
||||
icon={Link2Off}
|
||||
title="Could not load this shared session"
|
||||
description={loaded.message}
|
||||
/>
|
||||
{:else}
|
||||
<div class="flex flex-1 items-center justify-center py-16 text-tertiary">
|
||||
<Loader2 class="animate-spin" />
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
@@ -0,0 +1,72 @@
|
||||
<!--
|
||||
@component
|
||||
A shared session's preview panel: the artifacts the reader opened, one tab each, framed like a
|
||||
live session's preview panel. A share carries nothing else a tab could show.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { PanelRightClose } from 'lucide-svelte'
|
||||
import type { Snippet } from 'svelte'
|
||||
import DraggableTabs, { type TabItem } from '$lib/components/common/tabs/DraggableTabs.svelte'
|
||||
import ArtifactViewer from '$lib/components/copilot/chat/artifacts/ArtifactViewer.svelte'
|
||||
import type { PersistedArtifact } from '$lib/components/copilot/chat/artifacts/artifactsDB'
|
||||
|
||||
interface Props {
|
||||
tabs: PersistedArtifact[]
|
||||
activeId: string | undefined
|
||||
onSelect: (id: string) => void
|
||||
onClose: (id: string) => void
|
||||
onReorder: (ids: string[]) => void
|
||||
onCollapse: () => void
|
||||
/** Floats over the strip's right end, where a live session keeps its preview controls. */
|
||||
actions?: Snippet
|
||||
}
|
||||
|
||||
let { tabs, activeId, onSelect, onClose, onReorder, onCollapse, actions }: Props = $props()
|
||||
|
||||
const items = $derived<TabItem[]>(tabs.map((a) => ({ id: a.id, label: a.name, title: a.name })))
|
||||
// Measured so the strip reserves their width and no tab scrolls underneath them.
|
||||
let actionsWidth = $state(0)
|
||||
</script>
|
||||
|
||||
<div class="flex min-h-0 flex-1 flex-col p-2 pl-0">
|
||||
<div
|
||||
class="relative flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-light bg-surface"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onclick={onCollapse}
|
||||
title="Collapse preview"
|
||||
aria-label="Collapse preview"
|
||||
class="absolute left-1 top-1 z-30 inline-flex h-6 w-6 items-center justify-center rounded text-tertiary hover:bg-surface-hover hover:text-primary"
|
||||
>
|
||||
<PanelRightClose size={14} />
|
||||
</button>
|
||||
{#if actions}
|
||||
<div
|
||||
bind:clientWidth={actionsWidth}
|
||||
class="absolute right-1 top-0 z-30 flex h-8 items-center gap-1"
|
||||
>
|
||||
{@render actions()}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="shrink-0" style="--preview-actions-w: {actions ? actionsWidth + 8 : 8}px">
|
||||
<DraggableTabs
|
||||
tabs={items}
|
||||
activeId={activeId ?? ''}
|
||||
{onSelect}
|
||||
{onClose}
|
||||
onReorder={(order) => onReorder(order.map((t) => t.id))}
|
||||
class="session-preview-tab-strip h-8 border-b border-light bg-surface-secondary/50 pl-9 pr-[var(--preview-actions-w)]"
|
||||
/>
|
||||
</div>
|
||||
<!-- One viewer per tab, visibility-toggled as the live panel does, so switching tabs keeps
|
||||
each one's scroll position and source/preview choice. -->
|
||||
<div class="relative min-h-0 flex-1">
|
||||
{#each tabs as artifact (artifact.id)}
|
||||
<div class="absolute inset-0 {artifact.id === activeId ? '' : 'invisible'}">
|
||||
<ArtifactViewer {artifact} sharedCopy onPin={() => {}} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,193 @@
|
||||
<script lang="ts" module>
|
||||
import { lazyModule } from '$lib/lazyModule.svelte'
|
||||
|
||||
const diffDrawerModule = lazyModule(() => import('$lib/components/DiffDrawer.svelte'))
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { tick } from 'svelte'
|
||||
import { ExternalLink, GitCompareArrows, Lock } from 'lucide-svelte'
|
||||
import Badge from '$lib/components/common/badge/Badge.svelte'
|
||||
import RowIcon from '$lib/components/common/table/RowIcon.svelte'
|
||||
import type DiffDrawer from '$lib/components/DiffDrawer.svelte'
|
||||
import ArtifactsSegment from '$lib/components/copilot/chat/artifacts/ArtifactsSegment.svelte'
|
||||
import type { PersistedArtifact } from '$lib/components/copilot/chat/artifacts/artifactsDB'
|
||||
import { itemHref } from '$lib/components/copilot/chat/workspaceItems.svelte'
|
||||
import type { WindmillItemKind } from '$lib/components/copilot/chat/workspaceItems.svelte'
|
||||
import { fetchDeployedValueForDiff } from '$lib/components/otherUserDraftDiff'
|
||||
import { DraftService } from '$lib/gen'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import SessionStatusPopover from './SessionStatusPopover.svelte'
|
||||
import { editsToken } from './sessionDeployModel'
|
||||
import type { SharedSessionEdit } from './sessionSharing'
|
||||
import { TOKEN_TRIGGER_CLASS } from './SessionStatusToken.svelte'
|
||||
|
||||
interface Props {
|
||||
edits: SharedSessionEdit[]
|
||||
editsWorkspace: string | undefined
|
||||
/** The author's username. */
|
||||
author: string
|
||||
/** The reader may ask for the author's drafts in `editsWorkspace`. */
|
||||
readsDrafts: boolean
|
||||
/** Why the reader cannot, shown under the list once it is known. */
|
||||
draftsLockedReason: string | undefined
|
||||
/** Where the reader signs in to lift the lock, when they have no session. */
|
||||
draftsSignInHref?: string
|
||||
artifacts: PersistedArtifact[]
|
||||
openArtifact: (artifact: PersistedArtifact) => void
|
||||
}
|
||||
|
||||
let {
|
||||
edits,
|
||||
editsWorkspace,
|
||||
author,
|
||||
readsDrafts,
|
||||
draftsLockedReason,
|
||||
draftsSignInHref,
|
||||
artifacts,
|
||||
openArtifact
|
||||
}: Props = $props()
|
||||
|
||||
const token = $derived(
|
||||
editsToken({
|
||||
draft: edits.filter((e) => e.draft).length,
|
||||
deployed: edits.filter((e) => !e.draft).length
|
||||
})
|
||||
)
|
||||
|
||||
function deployedHref(edit: SharedSessionEdit): string | undefined {
|
||||
// Without it, `itemHref` would link the reader's own workspace's item at that path.
|
||||
if (edit.draft || !editsWorkspace) return undefined
|
||||
const kind = (edit.kind === 'raw_app' ? 'app' : edit.kind) as WindmillItemKind
|
||||
const href = itemHref(
|
||||
{ kind, path: edit.path, rawApp: edit.kind === 'raw_app' },
|
||||
editsWorkspace
|
||||
)
|
||||
return href.startsWith('#') ? undefined : href
|
||||
}
|
||||
|
||||
// Only these kinds share drafts across users (the server's `shares_drafts_across_users`);
|
||||
// the others stay private to their author. A never-deployed draft is stored under the
|
||||
// author's own path, which the server lets only them read.
|
||||
const SHARED_DRAFT_KINDS = new Set(['script', 'flow', 'app', 'raw_app'])
|
||||
function opensDraft(edit: SharedSessionEdit): boolean {
|
||||
return (
|
||||
edit.draft && readsDrafts && !!editsWorkspace && !!edit.draftPath && !draftPrivateReason(edit)
|
||||
)
|
||||
}
|
||||
|
||||
/** Why no reader but the author can open this draft, whoever the reader is. */
|
||||
function draftPrivateReason(edit: SharedSessionEdit): string | undefined {
|
||||
if (edit.draftOnly) return `Never deployed, so only ${author} can open this draft`
|
||||
if (!edit.draftKind || !SHARED_DRAFT_KINDS.has(edit.draftKind)) {
|
||||
return `Drafts of a ${edit.kind.replaceAll('_', ' ')} stay private to their author`
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const hasLockedRow = $derived(edits.some((e) => (e.draft ? !opensDraft(e) : !deployedHref(e))))
|
||||
|
||||
function rowTitle(edit: SharedSessionEdit): string {
|
||||
if (!edit.draft) {
|
||||
if (deployedHref(edit)) return `Open ${edit.path}`
|
||||
return draftsLockedReason ? `${edit.path}: ${draftsLockedReason}` : edit.path
|
||||
}
|
||||
if (opensDraft(edit)) return `View ${author}'s draft of ${edit.path}`
|
||||
return `${edit.path}: ${draftPrivateReason(edit) ?? draftsLockedReason ?? `only ${author} can open this draft`}`
|
||||
}
|
||||
|
||||
let editsOpen = $state(false)
|
||||
let diffDrawer: DiffDrawer | undefined = $state(undefined)
|
||||
|
||||
// The editor's own draft loading navigates, and leaving this page reloads it, which would
|
||||
// drop the loaded draft: the diff is read here instead, as the home page's draft badge does.
|
||||
async function viewDraft(edit: SharedSessionEdit) {
|
||||
if (!opensDraft(edit)) return
|
||||
const workspace = editsWorkspace!
|
||||
const kind = edit.draftKind!
|
||||
try {
|
||||
const [draft, deployed] = await Promise.all([
|
||||
DraftService.getDraftForUser({
|
||||
workspace,
|
||||
kind,
|
||||
path: edit.draftPath!,
|
||||
username: author
|
||||
}),
|
||||
fetchDeployedValueForDiff(workspace, kind, edit.path),
|
||||
diffDrawerModule.load()
|
||||
])
|
||||
await tick()
|
||||
diffDrawer?.openDrawer()
|
||||
diffDrawer?.setDiff({
|
||||
mode: 'simple',
|
||||
title: `${author}'s draft vs deployed`,
|
||||
original: deployed ?? {},
|
||||
current: draft.value as any
|
||||
})
|
||||
} catch (e: any) {
|
||||
sendUserToast(`Could not open the draft: ${e?.body ?? e?.message ?? e}`, true)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet lockedNote()}
|
||||
<div class="flex items-start gap-1.5 px-3 py-1 text-2xs text-secondary">
|
||||
<Lock size={11} class="mt-0.5 shrink-0" />
|
||||
<span>
|
||||
{draftsLockedReason}
|
||||
{#if draftsSignInHref}
|
||||
<a href={draftsSignInHref} class="font-medium text-accent hover:underline">Sign in</a>
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#if edits.length > 0 || artifacts.length > 0}
|
||||
<div class="flex items-center gap-3 rounded-md border bg-surface-tertiary px-2 py-2 text-xs">
|
||||
{#if edits.length > 0}
|
||||
<SessionStatusPopover
|
||||
bind:open={editsOpen}
|
||||
label={token.label}
|
||||
title="Edited this session"
|
||||
items={edits}
|
||||
itemKey={(e) => `${e.kind}:${e.path}`}
|
||||
itemHref={deployedHref}
|
||||
{rowTitle}
|
||||
itemDisabled={(edit) => (edit.draft ? !opensDraft(edit) : !deployedHref(edit))}
|
||||
onPick={(edit) => void viewDraft(edit)}
|
||||
triggerClass={`${TOKEN_TRIGGER_CLASS} ${token.class}`}
|
||||
widthClass="w-96"
|
||||
maxHeightClass="max-h-[min(9rem,50vh)]"
|
||||
footer={draftsLockedReason && hasLockedRow ? lockedNote : undefined}
|
||||
>
|
||||
{#snippet row(edit)}
|
||||
<RowIcon kind={edit.kind as any} path={edit.path} size={14} />
|
||||
<span class="min-w-0 flex-1 truncate font-mono font-normal text-primary">
|
||||
{edit.path}
|
||||
</span>
|
||||
{#if edit.draft}
|
||||
<Badge small color="indigo">{edit.draftOnly ? 'Draft only' : 'Draft'}</Badge>
|
||||
{#if opensDraft(edit)}
|
||||
<GitCompareArrows size={12} class="shrink-0 text-tertiary" />
|
||||
{:else}
|
||||
<Lock size={12} class="shrink-0 text-tertiary" />
|
||||
{/if}
|
||||
{:else}
|
||||
<Badge small color="green">Deployed</Badge>
|
||||
{#if deployedHref(edit)}
|
||||
<ExternalLink size={12} class="shrink-0 text-tertiary" />
|
||||
{/if}
|
||||
{/if}
|
||||
{/snippet}
|
||||
</SessionStatusPopover>
|
||||
{/if}
|
||||
{#if artifacts.length > 0}
|
||||
<ArtifactsSegment readOnly={{ artifacts, open: openArtifact }} />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if diffDrawerModule.current}
|
||||
{@const LoadedDiffDrawer = diffDrawerModule.current.default}
|
||||
<LoadedDiffDrawer bind:this={diffDrawer} />
|
||||
{/if}
|
||||
@@ -0,0 +1,52 @@
|
||||
<!--
|
||||
@component
|
||||
A shared session's name in the page header's breadcrumb, followed by who shared it and when.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { Globe, Share2 } from 'lucide-svelte'
|
||||
import Tooltip from '$lib/components/meltComponents/Tooltip.svelte'
|
||||
import { userColorClass, userInitials } from '$lib/components/userInitials'
|
||||
import { displayDate } from '$lib/utils'
|
||||
|
||||
let {
|
||||
name,
|
||||
author,
|
||||
sharedAt,
|
||||
isPublic = false
|
||||
}: { name: string; author?: string; sharedAt?: string; isPublic?: boolean } = $props()
|
||||
</script>
|
||||
|
||||
<span class="truncate text-xs font-normal text-emphasis" title={name}>{name}</span>
|
||||
{#if author}
|
||||
<Tooltip class="ml-2 inline-flex shrink-0 items-center">
|
||||
<span class="inline-flex items-center gap-1">
|
||||
<span class="inline-flex items-center gap-0.5 text-2xs font-normal text-hint">
|
||||
<Share2 size={10} aria-hidden="true" />Shared by
|
||||
</span>
|
||||
<span
|
||||
class="inline-flex h-4 w-4 items-center justify-center rounded-full text-[8px] font-semibold text-white {userColorClass(
|
||||
author
|
||||
)}"
|
||||
aria-label={author}
|
||||
>
|
||||
{userInitials(author)}
|
||||
</span>
|
||||
</span>
|
||||
{#snippet text()}
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span>Shared by <span class="font-medium">{author}</span></span>
|
||||
{#if sharedAt}
|
||||
<span class="opacity-80">{displayDate(sharedAt)}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
</Tooltip>
|
||||
{/if}
|
||||
{#if isPublic}
|
||||
<span
|
||||
class="ml-2 inline-flex shrink-0 items-center gap-0.5 text-2xs font-normal text-hint"
|
||||
title="Anyone with the link can read it"
|
||||
>
|
||||
<Globe size={10} aria-hidden="true" />Public
|
||||
</span>
|
||||
{/if}
|
||||
@@ -1,11 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { Button, Drawer, DrawerContent } from '$lib/components/common'
|
||||
import { FileText } from 'lucide-svelte'
|
||||
import { Pane, Splitpanes } from 'svelte-splitpanes'
|
||||
import type { Snippet } from 'svelte'
|
||||
import type { PersistedArtifact } from '$lib/components/copilot/chat/artifacts/artifactsDB'
|
||||
import SharedSessionStatusBar from './SharedSessionStatusBar.svelte'
|
||||
import SharedSessionPreview from './SharedSessionPreview.svelte'
|
||||
import AIChatMessage from '$lib/components/copilot/chat/AIChatMessage.svelte'
|
||||
import ToolGroupDisplay from '$lib/components/copilot/chat/ToolGroupDisplay.svelte'
|
||||
import ArtifactBody from '$lib/components/copilot/chat/artifacts/ArtifactBody.svelte'
|
||||
import DisplayCodeBlock from '$lib/components/copilot/chat/artifacts/DisplayCodeBlock.svelte'
|
||||
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
|
||||
import { BAR_TOP_PAD } from '$lib/components/pageHeaderRegistry.svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { splitterPointerCapture } from '$lib/utils/splitterPointerCapture'
|
||||
import { setChatViewHost } from '$lib/components/copilot/chat/chatViewHost'
|
||||
import { setUntrustedImages } from '$lib/components/copilot/chat/untrustedImages'
|
||||
import { readOnlyChatViewHost } from '$lib/components/copilot/chat/readOnlyChatViewHost.svelte'
|
||||
import { chatItemKey, groupToolRuns } from '$lib/components/copilot/chat/toolGroups'
|
||||
import type { DisplayMessage } from '$lib/components/copilot/chat/shared'
|
||||
@@ -15,37 +21,85 @@
|
||||
interface Props {
|
||||
snapshot: SessionSnapshot
|
||||
workspace: string
|
||||
author: string
|
||||
/** See SharedSessionStatusBar. */
|
||||
editsWorkspace?: string
|
||||
readsDrafts: boolean
|
||||
draftsLockedReason?: string
|
||||
draftsSignInHref?: string
|
||||
/** Under the status bar, at the foot of the chat column. */
|
||||
footer?: Snippet
|
||||
/** At the right end of the preview's tab strip while the panel is open. */
|
||||
previewActions?: Snippet
|
||||
}
|
||||
|
||||
let { snapshot, workspace }: Props = $props()
|
||||
let {
|
||||
snapshot,
|
||||
workspace,
|
||||
author,
|
||||
editsWorkspace,
|
||||
readsDrafts,
|
||||
draftsLockedReason,
|
||||
draftsSignInHref,
|
||||
footer,
|
||||
previewActions
|
||||
}: Props = $props()
|
||||
|
||||
let openArtifactId: string | undefined = $state(undefined)
|
||||
let drawer: Drawer | undefined = $state(undefined)
|
||||
setUntrustedImages()
|
||||
|
||||
let openIds: string[] = $state([])
|
||||
let activeId: string | undefined = $state(undefined)
|
||||
let chatSize = $state(100)
|
||||
let previewSize = $state(0)
|
||||
let previewWidth = $state(0)
|
||||
const collapsed = $derived(previewSize === 0)
|
||||
// As in a live session, the open panel owns the right edge from the top: the page header
|
||||
// stops where it starts and floats over the chat column, which pads itself to clear it.
|
||||
const headerInset = $derived(collapsed || previewWidth === 0 ? undefined : previewWidth)
|
||||
|
||||
// Built once: the page remounts this component for another share.
|
||||
const initial = untrack(() => ({ snapshot, workspace }))
|
||||
const artifacts: PersistedArtifact[] = initial.snapshot.artifacts.map((a) => ({
|
||||
...a,
|
||||
sessionId: '',
|
||||
createdAt: 0,
|
||||
updatedAt: a.updatedAt ?? 0
|
||||
}))
|
||||
setChatViewHost(
|
||||
readOnlyChatViewHost({
|
||||
messages: initial.snapshot.messages,
|
||||
workspace: initial.workspace,
|
||||
artifacts: initial.snapshot.artifacts.map((a) => ({
|
||||
...a,
|
||||
sessionId: '',
|
||||
createdAt: 0,
|
||||
updatedAt: 0
|
||||
})),
|
||||
artifacts,
|
||||
openArtifact: (id) => showArtifact(id)
|
||||
})
|
||||
)
|
||||
|
||||
function showArtifact(id: string) {
|
||||
openArtifactId = id
|
||||
drawer?.openDrawer()
|
||||
function setPreview(size: number) {
|
||||
previewSize = size
|
||||
chatSize = 100 - size
|
||||
}
|
||||
|
||||
function showArtifact(id: string) {
|
||||
if (!artifacts.some((a) => a.id === id)) {
|
||||
sendUserToast('This artifact was not part of the share.', true)
|
||||
return
|
||||
}
|
||||
if (!openIds.includes(id)) openIds = [...openIds, id]
|
||||
activeId = id
|
||||
if (collapsed) setPreview(50)
|
||||
}
|
||||
|
||||
function closeTab(id: string) {
|
||||
const at = openIds.indexOf(id)
|
||||
openIds = openIds.filter((t) => t !== id)
|
||||
if (activeId === id) activeId = openIds[Math.min(at, openIds.length - 1)]
|
||||
if (openIds.length === 0) setPreview(0)
|
||||
}
|
||||
|
||||
const openTabs = $derived(openIds.flatMap((id) => artifacts.find((a) => a.id === id) ?? []))
|
||||
|
||||
const messages = $derived(snapshot.messages)
|
||||
const chatItems = $derived(groupToolRuns(messages))
|
||||
const openArtifact = $derived(snapshot.artifacts.find((a) => a.id === openArtifactId))
|
||||
|
||||
// An answer's copy row shows once per turn, on its last answer, as in the live chat.
|
||||
const showsAnswerActions = $derived.by(() => {
|
||||
@@ -80,47 +134,75 @@
|
||||
{@render messageRow(message, messageIndex, true)}
|
||||
{/snippet}
|
||||
|
||||
{#if snapshot.artifacts.length > 0}
|
||||
<!-- The transcript only links plan documents; every other artifact is reached from here. -->
|
||||
<div class="mb-4 flex flex-wrap items-center gap-2 px-2">
|
||||
<span class="text-xs font-semibold text-emphasis">Artifacts</span>
|
||||
{#each snapshot.artifacts as artifact (artifact.id)}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="default"
|
||||
startIcon={{ icon: FileText }}
|
||||
onClick={() => showArtifact(artifact.id)}
|
||||
>
|
||||
{artifact.name}
|
||||
</Button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
<PageHeaderContent barRightInset={headerInset} />
|
||||
|
||||
<div class="flex flex-col pb-2">
|
||||
{#each chatItems as item (chatItemKey(item))}
|
||||
{#if item.kind === 'group'}
|
||||
<div class="mb-1 min-w-0 text-sm px-2 text-primary">
|
||||
<div class="px-[1px]">
|
||||
<ToolGroupDisplay group={item} entry={groupRow} />
|
||||
<!-- The live session's layout: the chat column, and beside it a preview panel that opens with the
|
||||
first artifact and collapses when its last tab closes. -->
|
||||
<div class="flex h-full min-h-0 flex-row" use:splitterPointerCapture>
|
||||
<Splitpanes
|
||||
horizontal={false}
|
||||
class="session-splitter min-h-0 flex-1 {collapsed ? 'splitter-off' : ''}"
|
||||
>
|
||||
<Pane
|
||||
bind:size={chatSize}
|
||||
minSize={25}
|
||||
class="flex min-h-0 flex-col {headerInset === undefined ? '' : BAR_TOP_PAD}"
|
||||
>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto">
|
||||
<!-- Fills the column so the bar rests at the bottom under a short transcript, where the
|
||||
live session keeps it above the composer, and sticks there under a long one. -->
|
||||
<div class="mx-auto flex min-h-full w-full max-w-3xl flex-col px-7 pt-4">
|
||||
<div class="flex flex-1 flex-col pb-2">
|
||||
{#each chatItems as item (chatItemKey(item))}
|
||||
{#if item.kind === 'group'}
|
||||
<div class="mb-1 min-w-0 text-sm px-2 text-primary">
|
||||
<div class="px-[1px]">
|
||||
<ToolGroupDisplay group={item} entry={groupRow} />
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
{@render messageRow(item.message, item.index, false)}
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<!-- The transcript only links plan documents, so every other artifact is reached
|
||||
from here. -->
|
||||
<div class="sticky bottom-0 bg-surface pb-3 pt-1">
|
||||
<SharedSessionStatusBar
|
||||
edits={snapshot.edits}
|
||||
{editsWorkspace}
|
||||
{author}
|
||||
{readsDrafts}
|
||||
{draftsLockedReason}
|
||||
{draftsSignInHref}
|
||||
{artifacts}
|
||||
openArtifact={(a) => showArtifact(a.id)}
|
||||
/>
|
||||
{@render footer?.()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
{@render messageRow(item.message, item.index, false)}
|
||||
{/if}
|
||||
{/each}
|
||||
</Pane>
|
||||
<Pane
|
||||
bind:size={previewSize}
|
||||
minSize={collapsed ? 0 : 30}
|
||||
maxSize={collapsed ? 0 : 75}
|
||||
class="flex min-h-0 flex-col"
|
||||
>
|
||||
{#if openTabs.length > 0}
|
||||
<div class="flex min-h-0 flex-1 flex-col" bind:clientWidth={previewWidth}>
|
||||
<SharedSessionPreview
|
||||
tabs={openTabs}
|
||||
{activeId}
|
||||
onSelect={(id) => (activeId = id)}
|
||||
onClose={closeTab}
|
||||
onReorder={(ids) => (openIds = ids)}
|
||||
onCollapse={() => setPreview(0)}
|
||||
actions={previewActions}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</Pane>
|
||||
</Splitpanes>
|
||||
</div>
|
||||
|
||||
<Drawer bind:this={drawer} size="900px">
|
||||
<DrawerContent title={openArtifact?.name ?? 'Artifact'} on:close={() => drawer?.closeDrawer()}>
|
||||
{#if openArtifact}
|
||||
<ArtifactBody
|
||||
content={openArtifact.content}
|
||||
source={openArtifact.kind !== 'md'}
|
||||
pre={DisplayCodeBlock}
|
||||
/>
|
||||
{:else}
|
||||
<span class="text-xs text-secondary">This artifact was not part of the share.</span>
|
||||
{/if}
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
|
||||
@@ -83,6 +83,24 @@ async function itemExists(kind: Kind, path: string, workspace: string): Promise<
|
||||
return pipelines.some((p) => p.folder === folder)
|
||||
}
|
||||
|
||||
/** The session's edits as its bar lists them, read once. */
|
||||
export async function readDeployItems(
|
||||
workspaceId: string,
|
||||
mask: Set<string>
|
||||
): Promise<DeployItem[]> {
|
||||
const draftItems = await getDraftItems(workspaceId)
|
||||
const keys = await Promise.all(
|
||||
maskOnlyCandidates({ draftItems, mask }).map((c) =>
|
||||
itemExists(c.deployKind, c.path, workspaceId).then(
|
||||
(exists) => (exists ? c.key : null),
|
||||
() => null
|
||||
)
|
||||
)
|
||||
)
|
||||
const existingKeys = new Set(keys.filter((k): k is string => !!k))
|
||||
return buildDeployItems({ draftItems, mask, existingKeys })
|
||||
}
|
||||
|
||||
/** Resolves which mask-only candidates still exist in the session workspace
|
||||
* (deployed) vs are gone (discarded drafts / deleted items) — the
|
||||
* `existingKeys` input of `buildDeployItems`. Undefined while resolving, so
|
||||
|
||||
@@ -200,6 +200,21 @@ export function badgeCounts(items: DeployItem[]): Record<BadgeKind, number> {
|
||||
return out
|
||||
}
|
||||
|
||||
/** The bar's edits token: drafts while any is pending, else the deployed count. */
|
||||
export function editsToken(counts: Record<BadgeKind, number>): { label: string; class: string } {
|
||||
return counts.draft > 0
|
||||
? {
|
||||
label: `${counts.draft} draft${counts.draft === 1 ? '' : 's'}`,
|
||||
class:
|
||||
'!bg-indigo-100 !text-indigo-800 hover:!bg-indigo-200 dark:!bg-indigo-700/40 dark:!text-indigo-100 dark:hover:!bg-indigo-600/40'
|
||||
}
|
||||
: {
|
||||
label: `${counts.deployed} deployed`,
|
||||
class:
|
||||
'!bg-green-100 !text-green-700 hover:!bg-green-200 dark:!bg-green-700/40 dark:!text-green-100 dark:hover:!bg-green-600/40'
|
||||
}
|
||||
}
|
||||
|
||||
// ── Action ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export type DeployOp = 'deploy_draft' | 'discard' | 'none'
|
||||
|
||||
@@ -54,6 +54,11 @@ describe('readSessionSnapshot', () => {
|
||||
})
|
||||
|
||||
it('reads a malformed snapshot as an empty one', () => {
|
||||
expect(readSessionSnapshot('nope')).toEqual({ messages: [], artifacts: [] })
|
||||
expect(readSessionSnapshot('nope')).toEqual({
|
||||
messages: [],
|
||||
artifacts: [],
|
||||
edits: [],
|
||||
editsWorkspace: undefined
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { DisplayMessage } from '$lib/components/copilot/chat/shared'
|
||||
import type { ImageMediaType } from '$lib/components/copilot/chat/imageUtils'
|
||||
import type { UserDraftItemKind } from '$lib/gen'
|
||||
import type {
|
||||
ArtifactKind,
|
||||
PersistedArtifact
|
||||
@@ -14,11 +15,33 @@ export type SharedSessionArtifact = {
|
||||
kind: ArtifactKind
|
||||
content: string
|
||||
role?: 'plan'
|
||||
/** Absent on a share made before they were kept. */
|
||||
updatedAt?: number
|
||||
version?: number
|
||||
approvedVersion?: number
|
||||
}
|
||||
|
||||
/** An item the session edited, as its bar listed it when shared. */
|
||||
export type SharedSessionEdit = {
|
||||
/** A deploy kind (`script`, `flow`, `http_trigger`, …). */
|
||||
kind: string
|
||||
/** The path it is shown and deployed at. */
|
||||
path: string
|
||||
draft: boolean
|
||||
/** Where the author's draft is stored, which a never-deployed item keeps apart from `path`.
|
||||
* Absent on a share made before they were kept. */
|
||||
draftKind?: UserDraftItemKind
|
||||
draftPath?: string
|
||||
draftOnly?: boolean
|
||||
}
|
||||
|
||||
export type SessionSnapshot = {
|
||||
messages: DisplayMessage[]
|
||||
artifacts: SharedSessionArtifact[]
|
||||
edits: SharedSessionEdit[]
|
||||
/** The workspace the edits live in: a fork, for a fork session's share, which is stored in
|
||||
* its parent. */
|
||||
editsWorkspace?: string
|
||||
}
|
||||
|
||||
export function sharedSessionUrl(workspaceId: string, shareId: string): string {
|
||||
@@ -27,6 +50,11 @@ export function sharedSessionUrl(workspaceId: string, shareId: string): string {
|
||||
)}/${encodeURIComponent(shareId)}`
|
||||
}
|
||||
|
||||
/** The share's page inside the app, for a reader who belongs to its workspace. */
|
||||
export function sharedSessionAppHref(workspaceId: string, shareId: string): string {
|
||||
return `/sessions/shared/${encodeURIComponent(shareId)}?workspace=${encodeURIComponent(workspaceId)}`
|
||||
}
|
||||
|
||||
/** A row as it reads once the turn is over: the viewer can neither wait on nor answer it. */
|
||||
function settled(message: DisplayMessage, keepImages: boolean): DisplayMessage {
|
||||
switch (message.role) {
|
||||
@@ -54,19 +82,25 @@ function settled(message: DisplayMessage, keepImages: boolean): DisplayMessage {
|
||||
*/
|
||||
export function buildSessionSnapshot(
|
||||
messages: DisplayMessage[],
|
||||
artifacts: PersistedArtifact[]
|
||||
artifacts: PersistedArtifact[],
|
||||
edits: { workspace: string; items: SharedSessionEdit[] } | undefined
|
||||
): SessionSnapshot {
|
||||
const sharedArtifacts: SharedSessionArtifact[] = artifacts.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
kind: a.kind,
|
||||
content: a.content,
|
||||
role: a.role
|
||||
role: a.role,
|
||||
updatedAt: a.updatedAt,
|
||||
version: a.version,
|
||||
approvedVersion: a.approvedVersion
|
||||
}))
|
||||
for (const keepImages of [true, false]) {
|
||||
const snapshot: SessionSnapshot = {
|
||||
messages: messages.map((m) => settled(m, keepImages)),
|
||||
artifacts: sharedArtifacts
|
||||
artifacts: sharedArtifacts,
|
||||
edits: edits?.items ?? [],
|
||||
editsWorkspace: edits?.workspace
|
||||
}
|
||||
if (new TextEncoder().encode(JSON.stringify(snapshot)).length <= MAX_SNAPSHOT_BYTES) {
|
||||
return snapshot
|
||||
@@ -162,8 +196,8 @@ function readMessage(m: Record<string, unknown>, index: number): DisplayMessage
|
||||
/**
|
||||
* A snapshot as the viewer may render it: rows rebuilt by {@link readMessage}, and an attached
|
||||
* image only from an inline data URL, since any other source would load a third-party resource
|
||||
* on behalf of whoever opens the link. Images inside rendered text are left to the viewer
|
||||
* page's `img-src` policy.
|
||||
* on behalf of whoever opens the link. Images inside rendered text are left to the transcript's
|
||||
* markdown renderers (`setUntrustedImages`).
|
||||
*/
|
||||
export function readSessionSnapshot(raw: unknown): SessionSnapshot {
|
||||
const snapshot = isRecord(raw) ? raw : {}
|
||||
@@ -183,7 +217,24 @@ export function readSessionSnapshot(raw: unknown): SessionSnapshot {
|
||||
name: a.name as string,
|
||||
kind: a.kind as ArtifactKind,
|
||||
content: a.content as string,
|
||||
role: a.role === 'plan' ? ('plan' as const) : undefined
|
||||
role: a.role === 'plan' ? ('plan' as const) : undefined,
|
||||
updatedAt: num(a.updatedAt),
|
||||
version: num(a.version),
|
||||
approvedVersion: num(a.approvedVersion)
|
||||
}))
|
||||
return { messages, artifacts }
|
||||
const edits = records(snapshot.edits)
|
||||
.filter((e) => typeof e.kind === 'string' && typeof e.path === 'string')
|
||||
.map((e) => ({
|
||||
kind: e.kind as string,
|
||||
path: e.path as string,
|
||||
draft: e.draft === true,
|
||||
draftKind: str(e.draftKind) as UserDraftItemKind | undefined,
|
||||
draftPath: str(e.draftPath),
|
||||
draftOnly: e.draftOnly === true
|
||||
}))
|
||||
return { messages, artifacts, edits, editsWorkspace: str(snapshot.editsWorkspace) }
|
||||
}
|
||||
|
||||
function num(value: unknown): number | undefined {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { resource } from 'runed'
|
||||
import { AiService, UserService } from '$lib/gen'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { readSessionSnapshot } from './sessionSharing'
|
||||
import { invalidateSharedSessions } from './sharedSessionsList.svelte'
|
||||
import { logSharedSessionOpen, logSharedSessionRemove } from './sharedSessionTelemetry'
|
||||
|
||||
export type LoadedSharedSession =
|
||||
| {
|
||||
state: 'found'
|
||||
session: Awaited<ReturnType<typeof AiService.getSharedAiSession>>
|
||||
snapshot: ReturnType<typeof readSessionSnapshot>
|
||||
}
|
||||
| { state: 'gone' }
|
||||
| { state: 'outsider'; email: string }
|
||||
| { state: 'error'; message: string }
|
||||
|
||||
/** Loads a share and stops sharing it. Nothing is fetched while `key` returns undefined. */
|
||||
export function useSharedSession(key: () => { workspace: string; id: string } | undefined) {
|
||||
const shared = resource(key, async (args): Promise<LoadedSharedSession | undefined> => {
|
||||
if (!args?.workspace || !args.id) return undefined
|
||||
try {
|
||||
const session = await AiService.getSharedAiSession(args)
|
||||
// Reading someone else's share is what lists it for the reader, and the sidebar may
|
||||
// have fetched its list before this read recorded it.
|
||||
if (!session.mine) {
|
||||
invalidateSharedSessions(args.workspace)
|
||||
logSharedSessionOpen(args.workspace)
|
||||
}
|
||||
return { state: 'found', session, snapshot: readSessionSnapshot(session.snapshot) }
|
||||
} catch (err) {
|
||||
const status = (err as { status?: number })?.status
|
||||
if (status === 401) {
|
||||
// The login page sends a signed-in user straight back to `rd`, so only a visitor
|
||||
// with no session goes there; anyone else is outside the share's workspace. The
|
||||
// server answers them alike whether or not the share exists, so the message must
|
||||
// not say that it does.
|
||||
const email = await UserService.getCurrentEmail().catch(() => undefined)
|
||||
if (email) return { state: 'outsider', email }
|
||||
const rd = window.location.pathname + window.location.search
|
||||
window.location.replace(`/user/login?rd=${encodeURIComponent(rd)}`)
|
||||
return undefined
|
||||
}
|
||||
// A malformed id is a 400 from the path extractor, and means the same to the reader.
|
||||
if (status === 404 || status === 400) return { state: 'gone' }
|
||||
return { state: 'error', message: String((err as { body?: unknown })?.body ?? err) }
|
||||
}
|
||||
})
|
||||
|
||||
const found = $derived(shared.current?.state === 'found' ? shared.current : undefined)
|
||||
let removing = $state(false)
|
||||
|
||||
async function stopSharing() {
|
||||
const workspace = key()?.workspace
|
||||
if (!found || !workspace) return
|
||||
removing = true
|
||||
try {
|
||||
await AiService.unshareAiSession({ workspace, id: found.session.id })
|
||||
shared.mutate({ state: 'gone' })
|
||||
invalidateSharedSessions(workspace)
|
||||
sendUserToast('Stopped sharing: the link no longer opens')
|
||||
} catch (err) {
|
||||
sendUserToast(`Could not stop sharing: ${(err as { body?: unknown })?.body ?? err}`, true)
|
||||
} finally {
|
||||
removing = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes the share out of the caller's sidebar; the link keeps working. */
|
||||
async function removeFromList(): Promise<boolean> {
|
||||
const workspace = key()?.workspace
|
||||
if (!found || !workspace) return false
|
||||
removing = true
|
||||
try {
|
||||
await AiService.forgetOpenedAiSession({ workspace, id: found.session.id })
|
||||
invalidateSharedSessions(workspace)
|
||||
logSharedSessionRemove('header', workspace)
|
||||
sendUserToast('Removed from your shared sessions')
|
||||
return true
|
||||
} catch (err) {
|
||||
sendUserToast(`Could not remove it: ${(err as { body?: unknown })?.body ?? err}`, true)
|
||||
return false
|
||||
} finally {
|
||||
removing = false
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get current() {
|
||||
return shared.current
|
||||
},
|
||||
get found() {
|
||||
return found
|
||||
},
|
||||
get removing() {
|
||||
return removing
|
||||
},
|
||||
stopSharing,
|
||||
removeFromList
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
|
||||
/** A reader opened someone else's shared session. The batch goes out on the share's workspace
|
||||
* route, which refuses anyone outside it, so only members are counted. */
|
||||
export function logSharedSessionOpen(workspace: string) {
|
||||
logFeatureUsage('ai_session', 'shared_open', { workspace })
|
||||
}
|
||||
|
||||
/** Where a reader took a share out of their sidebar list. */
|
||||
export type SharedSessionRemoveSource = 'header' | 'sidebar'
|
||||
|
||||
export function logSharedSessionRemove(source: SharedSessionRemoveSource, workspace: string) {
|
||||
logFeatureUsage('ai_session', 'shared_remove', { key: source, workspace })
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { resource } from 'runed'
|
||||
import { AiService } from '$lib/gen'
|
||||
|
||||
export type SharedSessionsFilter = 'show' | 'only' | 'hide'
|
||||
|
||||
export const SHARED_SESSIONS_FILTER_OPTIONS: {
|
||||
value: SharedSessionsFilter
|
||||
label: string
|
||||
hint: string
|
||||
}[] = [
|
||||
{ value: 'show', label: 'Show', hint: 'Show' },
|
||||
{ value: 'only', label: 'Only shared', hint: 'Only' },
|
||||
{ value: 'hide', label: 'Hide', hint: 'Hide' }
|
||||
]
|
||||
|
||||
// Bumped when this browser creates, changes, removes or opens a share, so a mounted list refetches.
|
||||
const versions: Record<string, number> = $state({})
|
||||
|
||||
export function invalidateSharedSessions(workspace: string | undefined): void {
|
||||
if (!workspace) return
|
||||
versions[workspace] = (versions[workspace] ?? 0) + 1
|
||||
}
|
||||
|
||||
/** The workspace's shares, as `listSharedAiSessions` returns them. Empty until it answers. */
|
||||
export function useSharedSessionsList(workspace: () => string | undefined) {
|
||||
const list = resource(
|
||||
() => {
|
||||
const ws = workspace()
|
||||
return { ws, v: ws ? (versions[ws] ?? 0) : 0 }
|
||||
},
|
||||
async ({ ws }) => {
|
||||
if (!ws) return []
|
||||
try {
|
||||
return await AiService.listSharedAiSessions({ workspace: ws })
|
||||
} catch (err) {
|
||||
// The list still works without them: they are an addition to the reader's own.
|
||||
console.error('Could not list the shared sessions', err)
|
||||
return []
|
||||
}
|
||||
}
|
||||
)
|
||||
return {
|
||||
get items() {
|
||||
return list.current ?? []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/** Two-letter initials; `john.doe` → `JD`, `alice` → `AL`, no username → `?`. */
|
||||
export function userInitials(username: string | null | undefined): string {
|
||||
if (!username) return '?'
|
||||
const parts = username.split(/[._\-\s]+/).filter(Boolean)
|
||||
if (parts.length >= 2) {
|
||||
return (parts[0][0] + parts[1][0]).toUpperCase()
|
||||
}
|
||||
return username.slice(0, 2).toUpperCase()
|
||||
}
|
||||
|
||||
// Deterministic, so a user's circle has the same color wherever it is drawn.
|
||||
const PALETTE = [
|
||||
'bg-blue-500',
|
||||
'bg-emerald-500',
|
||||
'bg-amber-500',
|
||||
'bg-rose-500',
|
||||
'bg-violet-500',
|
||||
'bg-cyan-500'
|
||||
]
|
||||
export function userColorClass(username: string | null | undefined): string {
|
||||
const name = username ?? ''
|
||||
let hash = 0
|
||||
for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) >>> 0
|
||||
return PALETTE[hash % PALETTE.length]
|
||||
}
|
||||
@@ -1454,27 +1454,6 @@
|
||||
{/snippet}
|
||||
|
||||
<style>
|
||||
/* Draggable gutter between the chat and the preview: a real (layout-occupying)
|
||||
10px-wide grab zone, no overlap tricks that could cover the chat's scrollbar
|
||||
or the preview's edge. Transparent at rest; on hover the app-global
|
||||
`.splitpanes__splitter::after` grabber fades in. Uses a dedicated class, not
|
||||
the shared `.splitter-hidden`, which force-zeroes splitter opacity and would
|
||||
hide that grabber. */
|
||||
:global(.splitpanes--vertical.session-splitter) > :global(.splitpanes__splitter) {
|
||||
background-color: transparent !important;
|
||||
border: none !important;
|
||||
width: 10px !important;
|
||||
}
|
||||
/* Inset the global hover grabber from the pane's top/bottom edges so the line
|
||||
doesn't run the full height, and round its ends into a pill — a lighter,
|
||||
more contained hint. */
|
||||
:global(.splitpanes--vertical.session-splitter) > :global(.splitpanes__splitter)::after {
|
||||
top: 8px !important;
|
||||
bottom: 8px !important;
|
||||
height: auto !important;
|
||||
border-radius: 9999px !important;
|
||||
}
|
||||
|
||||
/* The full-screen switch is the preview panel expanding to the left over the chat column, so
|
||||
the panes' widths are animated — but only while that switch is in flight (`panes-animating`),
|
||||
since a splitter drag sets the same inline width and would trail the pointer. */
|
||||
@@ -1484,11 +1463,4 @@
|
||||
which is there so a splitter drag tracks the pointer exactly. */
|
||||
transition: width var(--panes-move) cubic-bezier(0.33, 1, 0.68, 1) !important;
|
||||
}
|
||||
|
||||
/* Collapsed preview: the pane is resized to 0 but stays mounted, so remove
|
||||
the gutter entirely — it would otherwise leave a dead 10px drag zone on the
|
||||
chat's right edge. */
|
||||
:global(.splitpanes--vertical.splitter-off) > :global(.splitpanes__splitter) {
|
||||
display: none !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation'
|
||||
import { page } from '$app/state'
|
||||
import { EllipsisVertical, Link2Off, X } from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import DropdownV2 from '$lib/components/DropdownV2.svelte'
|
||||
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
|
||||
import SharedSessionBody from '$lib/components/sessions/SharedSessionBody.svelte'
|
||||
import SharedSessionTitle from '$lib/components/sessions/SharedSessionTitle.svelte'
|
||||
import { useSharedSession } from '$lib/components/sessions/sharedSession.svelte'
|
||||
import { resource } from 'runed'
|
||||
import { UserService } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
|
||||
const workspace = $derived(page.url.searchParams.get('workspace') ?? $workspaceStore ?? '')
|
||||
const id = $derived(page.params.id ?? '')
|
||||
|
||||
const shared = useSharedSession(() => ({ workspace, id }))
|
||||
// This URL is reachable by a signed-in user of another workspace when the share is public:
|
||||
// they get the standalone page's read-only presentation, with nothing to remove or open.
|
||||
const member = resource(
|
||||
() => workspace,
|
||||
(workspace) =>
|
||||
workspace
|
||||
? UserService.whoami({ workspace }).then(
|
||||
() => true,
|
||||
() => false
|
||||
)
|
||||
: Promise.resolve(false)
|
||||
)
|
||||
const isMember = $derived(member.current === true)
|
||||
const found = $derived(shared.found)
|
||||
const name = $derived(found?.session.name ?? 'Shared session')
|
||||
|
||||
// Staying would show the share still open, and reloading it would list it again.
|
||||
async function removeFromList() {
|
||||
if (await shared.removeFromList()) await goto('/')
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet sessionName()}
|
||||
<SharedSessionTitle
|
||||
{name}
|
||||
author={found?.session.created_by}
|
||||
sharedAt={found?.session.shared_at}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
{#snippet headerActions()}
|
||||
{#if found?.session.mine}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="default"
|
||||
destructive
|
||||
loading={shared.removing}
|
||||
onClick={shared.stopSharing}
|
||||
>
|
||||
Stop sharing
|
||||
</Button>
|
||||
{:else if found && isMember}
|
||||
<div class="flex items-center gap-1">
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="default"
|
||||
startIcon={{ icon: X }}
|
||||
loading={shared.removing}
|
||||
title="Remove it from Shared with you in the sidebar. The link keeps working."
|
||||
onClick={removeFromList}
|
||||
>
|
||||
Remove from my list
|
||||
</Button>
|
||||
<!-- An admin may take down a share made by someone else, which is moderation rather than
|
||||
the reader's own action. -->
|
||||
{#if found.session.can_unshare}
|
||||
<DropdownV2
|
||||
fixedHeight={false}
|
||||
placement="bottom-end"
|
||||
enableFlyTransition
|
||||
items={[
|
||||
{
|
||||
displayName: 'Stop sharing',
|
||||
description: 'Takes the link down for everyone. Allowed because you are an admin.',
|
||||
icon: Link2Off,
|
||||
type: 'delete',
|
||||
action: () => shared.stopSharing()
|
||||
}
|
||||
]}
|
||||
>
|
||||
{#snippet buttonReplacement()}
|
||||
<span
|
||||
class="inline-flex h-7 w-7 items-center justify-center rounded text-tertiary hover:bg-surface-hover hover:text-primary"
|
||||
title="More"
|
||||
>
|
||||
<EllipsisVertical size={14} />
|
||||
</span>
|
||||
{/snippet}
|
||||
</DropdownV2>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
<PageHeaderContent
|
||||
section={{ label: name, content: sessionName, noNavPicker: true }}
|
||||
actions={headerActions}
|
||||
actingWorkspaceId={workspace}
|
||||
/>
|
||||
|
||||
<div class="h-full min-h-0">
|
||||
<SharedSessionBody loaded={shared.current} {workspace} member={isMember} />
|
||||
</div>
|
||||
@@ -1,16 +1,21 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation'
|
||||
import { page } from '$app/state'
|
||||
import { resource } from 'runed'
|
||||
import { Globe, Link2Off, LogIn, MessagesSquare, Users } from 'lucide-svelte'
|
||||
import { Badge, Button, EmptyState, Skeleton } from '$lib/components/common'
|
||||
import { LogIn } from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import CenteredModal from '$lib/components/CenteredModal.svelte'
|
||||
import WindmillIcon from '$lib/components/icons/WindmillIcon.svelte'
|
||||
import SharedSessionTranscript from '$lib/components/sessions/SharedSessionTranscript.svelte'
|
||||
import { readSessionSnapshot } from '$lib/components/sessions/sessionSharing'
|
||||
import PageHeaderBar from '$lib/components/PageHeaderBar.svelte'
|
||||
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
|
||||
import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte'
|
||||
import SharedSessionBody from '$lib/components/sessions/SharedSessionBody.svelte'
|
||||
import SharedSessionTitle from '$lib/components/sessions/SharedSessionTitle.svelte'
|
||||
import { useSharedSession } from '$lib/components/sessions/sharedSession.svelte'
|
||||
import { sharedSessionAppHref } from '$lib/components/sessions/sessionSharing'
|
||||
import { applyDarkModeVariant } from '$lib/darkModeVariant'
|
||||
import { AiService } from '$lib/gen'
|
||||
import { UserService } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { displayDate } from '$lib/utils'
|
||||
|
||||
// Reached without signing in when the share is public, so this page sets up what the
|
||||
// logged-in layout otherwise would.
|
||||
@@ -27,131 +32,118 @@
|
||||
$workspaceStore = workspace
|
||||
})
|
||||
|
||||
type Loaded =
|
||||
| {
|
||||
state: 'found'
|
||||
session: Awaited<ReturnType<typeof AiService.getSharedAiSession>>
|
||||
snapshot: ReturnType<typeof readSessionSnapshot>
|
||||
}
|
||||
| { state: 'gone' }
|
||||
| { state: 'signin' }
|
||||
| { state: 'error'; message: string }
|
||||
|
||||
const shared = resource(
|
||||
() => ({ workspace, id }),
|
||||
async ({ workspace, id }): Promise<Loaded | undefined> => {
|
||||
if (!workspace || !id) return undefined
|
||||
try {
|
||||
const session = await AiService.getSharedAiSession({ workspace, id })
|
||||
return { state: 'found', session, snapshot: readSessionSnapshot(session.snapshot) }
|
||||
} catch (err) {
|
||||
const status = (err as { status?: number })?.status
|
||||
if (status === 401) return { state: 'signin' }
|
||||
// A malformed id is a 400 from the path extractor, and means the same to the reader.
|
||||
if (status === 404 || status === 400) return { state: 'gone' }
|
||||
return { state: 'error', message: String((err as { body?: unknown })?.body ?? err) }
|
||||
}
|
||||
// A member reads the share inside the app. Asked before the snapshot is fetched, so a member
|
||||
// does not download it twice.
|
||||
const member = resource(
|
||||
() => workspace,
|
||||
async (workspace) => {
|
||||
if (!workspace) return undefined
|
||||
const isMember = await UserService.whoami({ workspace }).then(
|
||||
() => true,
|
||||
() => false
|
||||
)
|
||||
if (isMember) await goto(sharedSessionAppHref(workspace, id), { replaceState: true })
|
||||
return isMember
|
||||
}
|
||||
)
|
||||
|
||||
const found = $derived(shared.current?.state === 'found' ? shared.current : undefined)
|
||||
const loginHref = $derived(
|
||||
`/user/login?rd=${encodeURIComponent(page.url.pathname + page.url.search)}`
|
||||
)
|
||||
const shared = useSharedSession(() => (member.current === false ? { workspace, id } : undefined))
|
||||
const found = $derived(shared.found)
|
||||
const name = $derived(found?.session.name ?? 'Shared AI session')
|
||||
|
||||
let removing = $state(false)
|
||||
async function stopSharing() {
|
||||
if (!found) return
|
||||
removing = true
|
||||
try {
|
||||
await AiService.unshareAiSession({ workspace, id: found.session.id })
|
||||
shared.mutate({ state: 'gone' })
|
||||
sendUserToast('Stopped sharing: the link no longer opens')
|
||||
} catch (err) {
|
||||
sendUserToast(`Could not stop sharing: ${(err as { body?: unknown })?.body ?? err}`, true)
|
||||
} finally {
|
||||
removing = false
|
||||
}
|
||||
}
|
||||
// Only a public share reaches a reader with no session. Signing in as a member brings them
|
||||
// back here, and on to the in-app page where the drafts open.
|
||||
const signedOut = resource(
|
||||
() => member.current === false,
|
||||
(nonMember) =>
|
||||
nonMember
|
||||
? UserService.getCurrentEmail().then(
|
||||
() => false,
|
||||
() => true
|
||||
)
|
||||
: Promise.resolve(false)
|
||||
)
|
||||
const rightInset = $derived(pageHeader.content?.barRightInset)
|
||||
const signInHref = $derived(
|
||||
signedOut.current
|
||||
? `/user/login?rd=${encodeURIComponent(page.url.pathname + page.url.search)}`
|
||||
: undefined
|
||||
)
|
||||
</script>
|
||||
|
||||
<!-- The transcript is its author's text, rendered to whoever holds the link: an image in it
|
||||
that points elsewhere would report every reader to that host. A policy stays with the
|
||||
document once set, so every link out of this page is a full load (`data-sveltekit-reload`). -->
|
||||
<svelte:head>
|
||||
<meta http-equiv="content-security-policy" content="img-src 'self' data: blob:" />
|
||||
</svelte:head>
|
||||
{#if member.current !== false}
|
||||
<CenteredModal title="Opening the shared session" loading />
|
||||
{:else}
|
||||
{#snippet sessionName()}
|
||||
<SharedSessionTitle
|
||||
{name}
|
||||
author={found?.session.created_by}
|
||||
sharedAt={found?.session.shared_at}
|
||||
isPublic={found?.session.is_public}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
<div class="flex min-h-screen flex-col bg-surface" data-sveltekit-reload>
|
||||
<div class="border-b bg-surface-secondary">
|
||||
<div class="mx-auto flex w-full max-w-3xl flex-wrap items-center gap-3 px-4 py-3">
|
||||
<WindmillIcon height="20px" width="20px" />
|
||||
{#if found}
|
||||
<div class="flex min-w-0 flex-1 flex-col">
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<h1 class="truncate text-sm font-semibold text-emphasis" title={found.session.name}>
|
||||
{found.session.name}
|
||||
</h1>
|
||||
{#if found.session.is_public}
|
||||
<Badge color="blue" icon={{ icon: Globe, position: 'left' }}>Public</Badge>
|
||||
{:else}
|
||||
<Badge color="gray" icon={{ icon: Users, position: 'left' }}>{workspace}</Badge>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="text-xs font-normal text-secondary">
|
||||
Read-only AI session shared by {found.session.created_by} · {displayDate(
|
||||
found.session.shared_at
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{#if found.session.can_unshare}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="default"
|
||||
destructive
|
||||
loading={removing}
|
||||
onClick={stopSharing}
|
||||
>
|
||||
Stop sharing
|
||||
</Button>
|
||||
{/if}
|
||||
{:else}
|
||||
<span class="text-sm font-semibold text-emphasis">Shared AI session</span>
|
||||
{/if}
|
||||
<!-- In the header while the preview is closed, and on the preview's tab strip while it is open,
|
||||
where the header no longer reaches. -->
|
||||
{#snippet headerActions()}
|
||||
{#if signInHref && rightInset === undefined}
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-2xs text-hint">Signed out</span>
|
||||
<Button unifiedSize="sm" variant="default" startIcon={{ icon: LogIn }} href={signInHref}>
|
||||
Sign in
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
{#snippet previewActions()}
|
||||
{#if signInHref}
|
||||
<span class="text-2xs text-hint">Signed out</span>
|
||||
<Button unifiedSize="xs" variant="default" startIcon={{ icon: LogIn }} href={signInHref}>
|
||||
Sign in
|
||||
</Button>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
<PageHeaderContent
|
||||
section={{ label: name, parent: workspace, content: sessionName, noNavPicker: true }}
|
||||
actions={headerActions}
|
||||
/>
|
||||
|
||||
<div class="relative flex h-screen flex-col bg-surface">
|
||||
<!-- `navHidden`: the reader may not be a member, so the bar offers no workspace to navigate.
|
||||
With the preview open the row floats and stops where the panel starts, as the app
|
||||
layout's header does beside a live session's panel. -->
|
||||
<div
|
||||
class="flex items-center bg-surface pl-4 {rightInset === undefined
|
||||
? 'shrink-0'
|
||||
: 'absolute left-0 top-0 z-30'}"
|
||||
style:right={rightInset === undefined ? undefined : `${rightInset}px`}
|
||||
>
|
||||
<a
|
||||
href="https://www.windmill.dev"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
title="windmill.dev"
|
||||
aria-label="Windmill website"
|
||||
class="shrink-0 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2"
|
||||
>
|
||||
<WindmillIcon height="20px" width="20px" />
|
||||
</a>
|
||||
<!-- `navHidden` pads the bar for a name that starts the row; here the icon does, so the
|
||||
name sits as far from it as the sidebar's "Windmill / Home" does from its icon. -->
|
||||
<div class="-ml-2 min-w-0 flex-1">
|
||||
<PageHeaderBar navHidden />
|
||||
</div>
|
||||
</div>
|
||||
<!-- The bar draws its bottom edge only while something inside `#content` is scrolled
|
||||
under it. -->
|
||||
<div id="content" class="min-h-0 flex-1">
|
||||
<SharedSessionBody
|
||||
loaded={shared.current}
|
||||
{workspace}
|
||||
{signInHref}
|
||||
previewActions={signInHref ? previewActions : undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mx-auto w-full max-w-3xl flex-1 px-4 py-6">
|
||||
{#if found}
|
||||
{#if found.snapshot.messages.length > 0}
|
||||
{#key found.session.id}
|
||||
<SharedSessionTranscript snapshot={found.snapshot} {workspace} />
|
||||
{/key}
|
||||
{:else}
|
||||
<EmptyState icon={MessagesSquare} title="This session has no messages" />
|
||||
{/if}
|
||||
{:else if shared.current?.state === 'signin'}
|
||||
<EmptyState
|
||||
icon={LogIn}
|
||||
title="Sign in to read this session"
|
||||
description="It is shared with the members of {workspace} only."
|
||||
>
|
||||
<Button variant="accent" unifiedSize="md" href={loginHref}>Sign in</Button>
|
||||
</EmptyState>
|
||||
{:else if shared.current?.state === 'gone'}
|
||||
<EmptyState
|
||||
icon={Link2Off}
|
||||
title="This shared session is not available"
|
||||
description="Its author stopped sharing it, or it is shared with another workspace's members only."
|
||||
/>
|
||||
{:else if shared.current?.state === 'error'}
|
||||
<EmptyState
|
||||
icon={Link2Off}
|
||||
title="Could not load this shared session"
|
||||
description={shared.current.message}
|
||||
/>
|
||||
{:else}
|
||||
<Skeleton layout={[[3], 1, [30]]} />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
Reference in New Issue
Block a user