Skip to content

Commit 72496bb

Browse files
simonwclaude
andcommitted
Merge main into claude/datasette-canned-query-approval-4lclqz
Resolves the agent_tools.py conflict by keeping both the stored query grant helpers from this branch and the AppEditToolset/_render_app changes from main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 parents 8d75c3e + 1588f13 commit 72496bb

13 files changed

Lines changed: 395 additions & 70 deletions

‎.github/workflows/publish.yml‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ jobs:
1212
runs-on: ubuntu-latest
1313
strategy:
1414
matrix:
15-
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
15+
python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"]
1616
steps:
17-
- uses: actions/checkout@v6
17+
- uses: actions/checkout@v7
1818
- name: Set up Python ${{ matrix.python-version }}
19-
uses: actions/setup-python@v6
19+
uses: actions/setup-python@v7
2020
with:
2121
python-version: ${{ matrix.python-version }}
2222
cache: pip
@@ -25,7 +25,7 @@ jobs:
2525
run: |
2626
pip install . --group dev
2727
- name: Cache Playwright browsers
28-
uses: actions/cache@v5
28+
uses: actions/cache@v6
2929
with:
3030
path: ~/.cache/ms-playwright/
3131
key: ${{ runner.os }}-browsers
@@ -42,9 +42,9 @@ jobs:
4242
permissions:
4343
id-token: write
4444
steps:
45-
- uses: actions/checkout@v6
45+
- uses: actions/checkout@v7
4646
- name: Set up Python
47-
uses: actions/setup-python@v6
47+
uses: actions/setup-python@v7
4848
with:
4949
python-version: "3.12"
5050
cache: pip

‎.github/workflows/test-playwright.yml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@ jobs:
2323
os: macos-latest
2424
install-command: python -m playwright install webkit
2525
steps:
26-
- uses: actions/checkout@v6
26+
- uses: actions/checkout@v7
2727
- name: Set up Python
28-
uses: actions/setup-python@v6
28+
uses: actions/setup-python@v7
2929
with:
3030
python-version: "3.13"
3131
cache: pip
@@ -34,7 +34,7 @@ jobs:
3434
run: |
3535
pip install . --group dev
3636
- name: Cache Playwright browsers
37-
uses: actions/cache@v5
37+
uses: actions/cache@v6
3838
with:
3939
path: |
4040
~/.cache/ms-playwright/

‎.github/workflows/test.yml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ jobs:
1010
runs-on: ubuntu-latest
1111
strategy:
1212
matrix:
13-
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
13+
python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"]
1414
steps:
15-
- uses: actions/checkout@v6
15+
- uses: actions/checkout@v7
1616
- name: Set up Python ${{ matrix.python-version }}
17-
uses: actions/setup-python@v6
17+
uses: actions/setup-python@v7
1818
with:
1919
python-version: ${{ matrix.python-version }}
2020
cache: pip

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,10 @@ The create and edit pages use Datasette's existing bundled CodeMirror editor for
115115

116116
The edit page includes a private checkbox, SQL query database access, stored query access, and allowed network origins. The network origins control is a free-form list for users with the `apps-set-csp` permission, a set of checkboxes when an `allowed_csp_origins` allow-list is configured, and hidden otherwise.
117117

118+
### Tagging apps in datasette-agent
119+
120+
If [datasette-agent](https://github.com/datasette/datasette-agent) is installed, apps can be tagged with `#` in a chat message. The autocomplete lists the apps you have permission to view, including external apps. The agent is told the tagged app's ID and URL and whether you can edit it. Its HTML source is not attached: the agent reads that using the `app_view` tool, which requires `edit-app` permission.
121+
118122
### External apps from plugins
119123

120124
Datasette plugins can register their own apps that are independent of the HTML sandbox system. This allows apps with more complex requirements to still participate in other features built around the app registry.

‎datasette_apps/__init__.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,12 @@ def register_agent_tools(datasette):
124124
from .agent_tools import get_app_edit_tools
125125

126126
return get_app_edit_tools(AgentTool, datasette)
127+
128+
129+
@hookimpl(optionalhook=True)
130+
def register_agent_reference_types(datasette):
131+
from datasette_agent.references import Reference, ReferenceType
132+
133+
from .agent_references import get_app_reference_types
134+
135+
return get_app_reference_types(ReferenceType, Reference)

‎datasette_apps/agent_references.py‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""Make apps taggable with # in datasette-agent chat messages."""
2+
3+
from urllib.parse import quote
4+
5+
from .agent_tools import search_allowed_apps
6+
from .permissions import AppResource
7+
from .registry import Registry
8+
9+
REFERENCE_INSTRUCTIONS = (
10+
"A tagged app's id is the app_id for the app_view, app_str_replace, "
11+
"app_insert, app_edit, app_render and app_debug tools, which require "
12+
"edit permission for that app. External apps cannot be edited."
13+
)
14+
15+
16+
def _app_reference_url(datasette, ref):
17+
# Has no database access, so it can't tell stored apps from external
18+
# ones - the launch route redirects to the right place for both, and
19+
# forwards full=1 for stored apps only.
20+
return datasette.urls.path(f"/-/apps/{quote(ref.id, safe=':')}/launch?full=1")
21+
22+
23+
async def _app_reference_context(datasette, actor, ref):
24+
# References come from the client, so the id can't be trusted
25+
app = await Registry(datasette).get_app(ref.id)
26+
if app is None or not await datasette.allowed(
27+
action="view-app", resource=AppResource(ref.id), actor=actor
28+
):
29+
return None
30+
lines = [f"URL: {datasette.urls.path(app['path'])}"]
31+
if app["external"]:
32+
lines.append("External app registered by a plugin; it cannot be edited.")
33+
else:
34+
can_edit = await datasette.allowed(
35+
action="edit-app", resource=AppResource(ref.id), actor=actor
36+
)
37+
lines.append(f"Current version: {app['current_version']}")
38+
lines.append(
39+
"The user can edit this app."
40+
if can_edit
41+
else "The user can view this app but not edit it, so its source "
42+
"is not available to the app tools."
43+
)
44+
return "\n".join(lines)
45+
46+
47+
def get_app_reference_types(ReferenceType, Reference):
48+
async def search(datasette, actor, q, limit):
49+
rows = await search_allowed_apps(
50+
datasette, actor, "view-app", query=q, limit=limit, stored_only=False
51+
)
52+
return [
53+
Reference(
54+
type="app",
55+
id=row["id"],
56+
name=row["name"],
57+
description=row["description"] or "",
58+
)
59+
for row in rows
60+
]
61+
62+
return [
63+
ReferenceType(
64+
type="app",
65+
label="app",
66+
search=search,
67+
url=_app_reference_url,
68+
instructions=REFERENCE_INSTRUCTIONS,
69+
context=_app_reference_context,
70+
)
71+
]

‎datasette_apps/agent_tools.py‎

Lines changed: 71 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -188,38 +188,17 @@ async def delete(self, ref):
188188
raise NotImplementedError("Use the datasette-apps delete page to delete apps")
189189

190190

191-
def _render_app(editable):
192-
metadata = editable.metadata
193-
name = html.escape(metadata.get("name") or metadata["app_id"])
194-
path = html.escape(metadata["path"], quote=True)
195-
edit_path = html.escape(f"{metadata['path']}/edit", quote=True)
196-
version = html.escape(str(editable.version))
197-
return {
198-
"_html": (
199-
'<div class="datasette-app-agent-tool">'
200-
'<span class="datasette-app-agent-tool-status">'
201-
f"<strong>{name}</strong> updated to v{version}."
202-
"</span>"
203-
'<span class="datasette-app-agent-tool-actions">'
204-
f'<a class="datasette-app-button" href="{path}">View app</a>'
205-
f'<a class="datasette-app-button" href="{edit_path}">Edit</a>'
206-
"</span>"
207-
"</div>"
208-
),
209-
}
210-
211-
212-
def _render_created_app(app, view_path, edit_path):
213-
name = html.escape(app["name"] or app["id"])
214-
path = html.escape(view_path, quote=True)
191+
def _app_widget_html(name, status, view_path, edit_path):
192+
name = html.escape(name)
193+
view_path = html.escape(f"{view_path}?full=1", quote=True)
215194
edit_path = html.escape(edit_path, quote=True)
216195
return (
217196
'<div class="datasette-app-agent-tool">'
218197
'<span class="datasette-app-agent-tool-status">'
219-
f"<strong>{name}</strong> created."
198+
f"<strong>{name}</strong>{status}"
220199
"</span>"
221200
'<span class="datasette-app-agent-tool-actions">'
222-
f'<a class="datasette-app-button" href="{path}">View app</a>'
201+
f'<a class="datasette-app-button" href="{view_path}">View app</a>'
223202
f'<a class="datasette-app-button" href="{edit_path}">Edit</a>'
224203
"</span>"
225204
"</div>"
@@ -362,8 +341,44 @@ async def _approve_write_queries(context, app_name, queries):
362341
return None
363342

364343

344+
def _render_app(editable, status=None):
345+
metadata = editable.metadata
346+
if status is None:
347+
status = f" updated to v{html.escape(str(editable.version))}."
348+
return {
349+
"_html": _app_widget_html(
350+
metadata.get("name") or metadata["app_id"],
351+
status,
352+
metadata["path"],
353+
f"{metadata['path']}/edit",
354+
),
355+
}
356+
357+
358+
def _render_app_unchanged(editable):
359+
return _render_app(
360+
editable, status=f" v{html.escape(str(editable.version))}."
361+
)
362+
363+
364+
def _render_created_app(app, view_path, edit_path):
365+
return _app_widget_html(app["name"] or app["id"], " created.", view_path, edit_path)
366+
367+
368+
class AppEditToolset(EditToolset):
369+
"""The render tool only displays the app, so its status must not claim
370+
the app was updated."""
371+
372+
async def render(self, external_id):
373+
self.render_hook = _render_app_unchanged
374+
try:
375+
return await super().render(external_id)
376+
finally:
377+
self.render_hook = _render_app
378+
379+
365380
def _toolset(datasette, actor):
366-
return EditToolset(
381+
return AppEditToolset(
367382
StoredAppHtmlStore(datasette, actor),
368383
name_prefix="app",
369384
id_field="app_id",
@@ -433,42 +448,35 @@ async def _app_create(
433448
)
434449

435450

436-
async def _app_list(datasette, actor, query=None, limit=10):
437-
try:
438-
limit = int(limit)
439-
except (TypeError, ValueError):
440-
return _error("limit must be an integer between 1 and 20")
441-
if limit < 1 or limit > 20:
442-
return _error("limit must be an integer between 1 and 20")
451+
async def search_allowed_apps(
452+
datasette, actor, action, query=None, limit=10, stored_only=True
453+
):
454+
"""Apps the actor can perform action on, best matches first.
443455
456+
Filters on permissions in SQL so that limit applies to allowed apps. A
457+
query with no searchable tokens matches nothing.
458+
"""
444459
await Registry(datasette).ensure_tables()
445460
allowed_sql, allowed_params = await datasette.allowed_resources_sql(
446-
action="edit-app", actor=actor
461+
action=action, actor=actor
447462
)
448-
query = query.strip() if isinstance(query, str) else None
449463
actor_id = _actor_id(actor)
450464
params = dict(allowed_params)
451465
params.update(
452466
{
453467
"current_actor_id": actor_id,
454-
"fetch_limit": limit + 1,
468+
"limit": limit,
455469
}
456470
)
457471

458472
join_search = ""
459473
search_filter = ""
460474
search_order = ""
475+
stored_filter = "AND apps.external = 0" if stored_only else ""
461476
if query:
462477
fts_query = _fts_query(query)
463478
if not fts_query:
464-
return json.dumps(
465-
{
466-
"query": query,
467-
"apps": [],
468-
"returned_count": 0,
469-
"has_more": False,
470-
}
471-
)
479+
return []
472480
join_search = "JOIN apps_fts ON apps.rowid = apps_fts.rowid"
473481
search_filter = "AND apps_fts MATCH :fts_query"
474482
search_order = """
@@ -487,7 +495,7 @@ async def _app_list(datasette, actor, query=None, limit=10):
487495
}
488496
)
489497

490-
rows = (
498+
return (
491499
await datasette.get_internal_database().execute(
492500
"""
493501
WITH allowed_apps AS (
@@ -515,24 +523,39 @@ async def _app_list(datasette, actor, query=None, limit=10):
515523
ON app_user_state.app_id = apps.id
516524
AND app_user_state.actor_id = :current_actor_id
517525
WHERE apps.deleted_at IS NULL
518-
AND apps.external = 0
526+
{stored_filter}
519527
{search_filter}
520528
ORDER BY
521529
{search_order}
522530
app_user_state.pinned_at IS NOT NULL DESC,
523531
app_user_state.last_accessed_at DESC,
524532
apps.updated_at DESC,
525533
apps.id
526-
LIMIT :fetch_limit
534+
LIMIT :limit
527535
""".format(
528536
allowed_sql=allowed_sql,
529537
join_search=join_search,
538+
stored_filter=stored_filter,
530539
search_filter=search_filter,
531540
search_order=search_order,
532541
),
533542
params,
534543
)
535544
).rows
545+
546+
547+
async def _app_list(datasette, actor, query=None, limit=10):
548+
try:
549+
limit = int(limit)
550+
except (TypeError, ValueError):
551+
return _error("limit must be an integer between 1 and 20")
552+
if limit < 1 or limit > 20:
553+
return _error("limit must be an integer between 1 and 20")
554+
555+
query = query.strip() if isinstance(query, str) else None
556+
rows = await search_allowed_apps(
557+
datasette, actor, "edit-app", query=query, limit=limit + 1
558+
)
536559
has_more = len(rows) > limit
537560
apps = [
538561
{

‎datasette_apps/views.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -790,7 +790,10 @@ async def launch_app(datasette, request):
790790
raise NotFound("App not found")
791791
await _ensure_app_permission(datasette, actor, "view-app", app_id)
792792
if not app["external"]:
793-
return Response.redirect(app["path"])
793+
path = app["path"]
794+
if request.args.get("full") == "1":
795+
path = f"{path}?full=1"
796+
return Response.redirect(path)
794797
if actor:
795798
await registry.record_access(_actor_id(actor), app_id)
796799
return Response.redirect(app["path"])

‎pyproject.toml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@ license = "Apache-2.0"
88
classifiers=[
99
"Framework :: Datasette"
1010
]
11-
requires-python = ">=3.10"
11+
requires-python = ">=3.11"
1212
dependencies = [
13-
"datasette>=1.0a37",
13+
"datasette>=1.0a41",
1414
"datasette-agent-edit>=0.1a0",
1515
]
1616

1717
[dependency-groups]
1818
dev = [
19-
"datasette-agent>=0.4a0",
19+
"datasette-agent>=0.5a0",
2020
"playwright>=1.60.0",
2121
"pytest",
2222
"pytest-asyncio",

0 commit comments

Comments
 (0)