Compare commits

...

28 Commits

Author SHA1 Message Date
063b2ccdc8 (broken) add json parsing for ai 2026-05-01 19:01:31 +00:00
f4221e27ac fix(ai): fix leak from ai_get_provider_key
Some checks failed
CI Code / Check spelling (pull_request) Successful in 1m7s
CI Code / Check coding style (pull_request) Successful in 1m54s
CI Code / Linux (debian) (pull_request) Failing after 3m0s
CI Code / Linux (arch) (pull_request) Failing after 3m7s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m8s
CI Code / Code Coverage (pull_request) Successful in 2m53s
2026-05-01 18:50:21 +00:00
cdcc45b7c6 ref(pref): add newline at the end of the file 2026-05-01 18:47:46 +00:00
f133d81a05 fix(ai): use atomic operations for refcounting
Some checks failed
CI Code / Check coding style (pull_request) Successful in 1m8s
CI Code / Check spelling (pull_request) Successful in 1m7s
CI Code / Linux (debian) (pull_request) Failing after 2m58s
CI Code / Linux (arch) (pull_request) Failing after 3m7s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m8s
CI Code / Code Coverage (pull_request) Successful in 2m54s
Replace plain ref_count++/-- with g_atomic_int_inc and
g_atomic_int_dec_and_test for both AIProvider and AISession refcounts.
Prevents data races when ref/unref is called from worker threads.
2026-05-01 18:24:57 +00:00
a16237d16b fix(ai): convert \n escape sequences to actual newlines in LLM responses
Some checks failed
CI Code / Check spelling (pull_request) Successful in 51s
CI Code / Check coding style (pull_request) Successful in 1m7s
CI Code / Linux (debian) (pull_request) Failing after 2m56s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m5s
CI Code / Linux (arch) (pull_request) Failing after 3m5s
CI Code / Code Coverage (pull_request) Successful in 2m59s
2026-05-01 18:21:47 +00:00
cfe6ea46e2 feat(ai): disable request storage via store:false parameter
Some checks failed
CI Code / Check coding style (pull_request) Successful in 1m22s
CI Code / Linux (arch) (pull_request) Failing after 3m12s
CI Code / Check spelling (pull_request) Successful in 1m50s
CI Code / Linux (debian) (pull_request) Failing after 2m52s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m4s
CI Code / Code Coverage (pull_request) Successful in 2m49s
Add store:false to AI API requests to prevent OpenAI, Perplexity, and
other providers from storing conversation data or using it for training.

Both the OpenAI Responses API and Perplexity API support the store
parameter to control whether requests are persisted. Setting it to false
ensures conversations remain private and are not retained by the provider.

Privacy:
- Requests are not stored by AI providers
- Conversations are not used for model training
- Aligns with CProof's privacy-first design
2026-05-01 17:05:44 +00:00
2fc7f3d672 fix(ai): validate aiwin pointer to prevent UAF when window closed
Some checks failed
CI Code / Check spelling (pull_request) Successful in 53s
CI Code / Check coding style (pull_request) Successful in 1m11s
CI Code / Linux (debian) (pull_request) Failing after 2m58s
CI Code / Linux (arch) (pull_request) Failing after 3m11s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m10s
CI Code / Code Coverage (pull_request) Successful in 2m46s
Prevent use-after-free in the AI request worker thread when the user
closes the AI window during the 60-second HTTP request timeout. Without
this fix, the worker may dereference a dangling pointer and crash or
exhibit undefined behavior.

The _ai_request_thread function in ai_client.c previously cast user_data
to ProfAiWin* and used it directly without verifying the window was still
alive. Added wins_ai_exists() to iterate through all AI windows and check
if the pointer is still valid before use.

Safety:
- wins_ai_exists() iterates all AI windows (handles multiple AI windows)
- Worker skips UI update if window was freed, just cleans up
- Logs warning when dangling pointer is detected
2026-05-01 17:03:47 +00:00
fe0a46da58 refactor(ai): add UI display helpers
Some checks failed
CI Code / Check spelling (pull_request) Successful in 54s
CI Code / Check coding style (pull_request) Successful in 2m4s
CI Code / Linux (debian) (pull_request) Failing after 2m56s
CI Code / Linux (arch) (pull_request) Failing after 3m10s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m9s
CI Code / Code Coverage (pull_request) Successful in 2m55s
Add static _aiwin_display_error() and
_aiwin_display_response() helpers to reduce mutex repetition and
log warnings when aiwin is NULL or invalid.
2026-05-01 16:36:07 +00:00
cead417e78 refactor(ai): remove redundant callback layer from AI client
Some checks failed
CI Code / Check spelling (pull_request) Successful in 53s
CI Code / Check coding style (pull_request) Successful in 1m8s
CI Code / Linux (debian) (pull_request) Failing after 2m55s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m4s
CI Code / Linux (arch) (pull_request) Failing after 3m7s
CI Code / Code Coverage (pull_request) Successful in 2m42s
The ai_response_cb and ai_error_cb parameters were always passed the
same functions (aiwin_display_response and aiwin_display_error),
making the callback indirection redundant and complicating the call
chain.

Remove ai_callback_data_t, _ai_callback_invoke(), and
_ai_invoke_callback(). Simplify _ai_request_thread and ai_send_prompt
to directly call aiwin_display_error() and aiwin_display_response()
when user_data is a valid ProfAiWin*.
2026-05-01 13:34:00 +00:00
00f11eb704 fix(ai): guard NULL search_str and update tests for new cycling behavior
Some checks failed
CI Code / Check spelling (pull_request) Successful in 21s
CI Code / Check coding style (pull_request) Successful in 37s
CI Code / Linux (debian) (pull_request) Failing after 2m56s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m7s
CI Code / Code Coverage (pull_request) Successful in 2m55s
CI Code / Linux (arch) (pull_request) Failing after 3m45s
Update ai_providers_find() to handle NULL search_str safely by treating it
as an empty string, preventing a segfault in strdup() within autocomplete_complete().

Rename test_ai_providers_find_case_sensitive to test_ai_providers_find_case_insensitive
to reflect the new case-insensitive matching contract. Update all affected tests to
expect cycling behavior (NULL/empty returns first provider) and use auto_gchar for
automatic memory management.

Use `gchar` instead of `char` in ai_providers_find for consistency
2026-05-01 13:08:28 +00:00
4913a3d5a4 ref(ai): remove inaccurate logging 2026-05-01 12:56:57 +00:00
634fb7d7eb fix(ai): standardize lock handling in _ai_invoke_callback
Some checks failed
CI Code / Check spelling (pull_request) Successful in 20s
CI Code / Check coding style (pull_request) Successful in 34s
CI Code / Code Coverage (pull_request) Failing after 1m6s
CI Code / Linux (debian) (pull_request) Failing after 2m59s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m11s
CI Code / Linux (arch) (pull_request) Failing after 3m19s
Take the global lock mutex before invoking all callbacks (success
and error) to ensure thread-safety. Previously some paths took the
lock and others did not, creating asymmetric behavior that could
lead to data races when callbacks access UI state.
2026-05-01 11:35:09 +00:00
461c0c32dd refactor(ai): use stateful autocomplete for provider name matching
Some checks failed
CI Code / Check spelling (pull_request) Successful in 57s
CI Code / Check coding style (pull_request) Successful in 1m4s
CI Code / Code Coverage (pull_request) Failing after 1m7s
CI Code / Linux (debian) (pull_request) Failing after 2m58s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m9s
CI Code / Linux (arch) (pull_request) Failing after 3m47s
Replace the manual GHashTable iteration in ai_providers_find() with the
existing stateful autocomplete system. Provider names are now kept in
sync via autocomplete_add/remove during ai_add_provider/ai_remove_provider,
and ai_providers_find delegates to autocomplete_complete() for deterministic
tab-completion cycling through sorted results.

This eliminates manual GList allocation, iteration, and cleanup, while
providing consistent forward/backward cycling behavior shared by all
autocomplete callers.
2026-04-30 23:16:12 +00:00
002a6ed15b refactor(ai): flatten autocomplete into sequential prefix-matching chain
Some checks failed
CI Code / Check spelling (pull_request) Successful in 1m5s
CI Code / Check coding style (pull_request) Successful in 2m7s
CI Code / Linux (arch) (pull_request) Failing after 3m9s
CI Code / Code Coverage (pull_request) Successful in 2m54s
CI Code / Linux (debian) (pull_request) Successful in 4m28s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m41s
Replace the deeply nested conditional tree in _ai_autocomplete() with a
flat sequential chain of autocomplete_param_with_*() calls. Each call
tries a specific command prefix (e.g., "/ai set provider", "/ai start")
and returns immediately on match — a common, reliable pattern for
command-line tab completion.

The previous design nested provider-name autocomplete inside
g_strv_length() and g_strcmp0() checks, meaning /ai<tab> and /ai <tab>
would never reach the subcommand matcher. The new flat structure ensures
every prefix is tried in order, with the most specific prefixes first
and the generic /ai subcommand fallback last.

This pattern — sequential prefix matching with early return — is the
standard approach for autocomplete dispatch: each handler owns its
prefix, no shared state or argument parsing is needed, and adding a
new subcommand is a single append to the chain.
2026-04-30 23:10:14 +00:00
dc75f16221 fix(ai): move generic subcommand autocomplete outside nested conditionals
Some checks failed
CI Code / Check spelling (pull_request) Successful in 22s
CI Code / Check coding style (pull_request) Successful in 1m8s
CI Code / Linux (arch) (pull_request) Failing after 3m7s
CI Code / Code Coverage (pull_request) Successful in 2m58s
CI Code / Linux (debian) (pull_request) Successful in 4m22s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m35s
The generic `/ai <subcommand>` tab-completion was nested inside conditional
blocks that prevented it from firing in common cases — for example,
`/ai<tab>` or `/ai <tab>` would never match subcommands because the
`autocomplete_param_with_ac()` call was guarded by argument count checks
and nested inside the explicit handler branches.

Move the fallback subcommand autocomplete to execute unconditionally after
all explicit handler branches, ensuring `/ai <tab>` always lists available
subcommands regardless of argument count or which subcommand was typed.

Also move the `/ai set` subcommand fallback outside the inner else-block
so it runs whenever args[0] is "set", not only when num_args >= 2.
2026-04-30 22:51:07 +00:00
da0bf43d73 fix(ai): join multi-word arguments in cmd_ai_correct
Some checks failed
CI Code / Check spelling (pull_request) Successful in 24s
CI Code / Check coding style (pull_request) Successful in 37s
CI Code / Linux (arch) (pull_request) Failing after 3m7s
CI Code / Code Coverage (pull_request) Successful in 2m57s
CI Code / Linux (debian) (pull_request) Successful in 4m24s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m37s
Use g_strjoinv to join all arguments from args[1] onwards into a
single prompt string. Previously only args[1] was used, truncating
multi-word prompts like '/ai correct hello world' to just 'hello'
2026-04-30 19:24:39 +00:00
9e1f9b666e fix(ai): fix provider_name leak and const-cast in cmd_ai_start
Some checks failed
CI Code / Check spelling (pull_request) Successful in 55s
CI Code / Linux (arch) (pull_request) Failing after 3m25s
CI Code / Check coding style (pull_request) Successful in 1m38s
CI Code / Linux (debian) (pull_request) Successful in 4m42s
CI Code / Code Coverage (pull_request) Successful in 2m50s
CI Code / Linux (ubuntu) (pull_request) Successful in 8m12s
Use auto_gchar temporary for g_strndup result in cmd_ai_start to
prevent memory leak. Fix const-cast warning by using a proper
non-const temporary variable.
2026-04-30 19:14:49 +00:00
93ad7379e2 fix(ai): align ai_list_providers with documented contract
All checks were successful
CI Code / Check coding style (pull_request) Successful in 48s
CI Code / Check spelling (pull_request) Successful in 33s
CI Code / Linux (debian) (pull_request) Successful in 4m47s
CI Code / Linux (arch) (pull_request) Successful in 5m29s
CI Code / Code Coverage (pull_request) Successful in 2m45s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m29s
Remove ai_provider_ref() from ai_list_providers() so the returned
providers do not need to be unref'd by the caller. This matches the
header docstring which states "caller must not free the list or
providers". Also update all callers (cmd_ai_providers, tests) to
remove redundant ai_provider_unref() calls.
2026-04-30 19:09:46 +00:00
caa0b3ccba fix(ai): remove redundant g_strdup on api_key assignment
Some checks failed
CI Code / Check coding style (pull_request) Successful in 37s
CI Code / Check spelling (pull_request) Successful in 21s
CI Code / Linux (arch) (pull_request) Failing after 3m12s
CI Code / Code Coverage (pull_request) Successful in 2m47s
CI Code / Linux (debian) (pull_request) Successful in 4m21s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m53s
ai_get_provider_key() already returns a freshly g_strdup'd copy of
the API key. The outer g_strdup in ai_session_create() created an
unnecessary second copy, leaking the original pointer.
2026-04-30 19:06:49 +00:00
c9a5239117 fix(ai): remove API key from debug log
Some checks failed
CI Code / Check spelling (pull_request) Successful in 22s
CI Code / Check coding style (pull_request) Successful in 37s
CI Code / Linux (debian) (pull_request) Failing after 2m59s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m10s
CI Code / Code Coverage (pull_request) Successful in 2m58s
CI Code / Linux (arch) (pull_request) Failing after 3m59s
Remove the log_debug line in ai_client.c that leaked the first 10
characters of the API key into logs. This is also contained a memory leak (g_strndup
return value was never freed).
2026-04-30 19:05:33 +00:00
25e0459979 fix(ai): persist API keys to disk after set/remove operations
API keys set via /ai set token were only stored in memory and lost
on client restart. prefs_ai_set_token() and prefs_ai_remove_token()
mutated the in-memory prefs but never called _save_prefs(), unlike
other preference setters in the same file.

Both functions now call _save_prefs() after mutating the keyfile,
ensuring API keys persist across client restarts as advertised.
2026-04-30 19:01:10 +00:00
bccd3ecded fix(ai): remove duplicate assistant response in the message history
Some checks failed
CI Code / Check coding style (pull_request) Successful in 44s
CI Code / Linux (debian) (pull_request) Failing after 2m59s
CI Code / Linux (arch) (pull_request) Failing after 3m7s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m7s
CI Code / Check spelling (pull_request) Successful in 17s
CI Code / Code Coverage (pull_request) Successful in 2m46s
2026-04-30 18:05:51 +00:00
cff05ca802 ref(ai): move unfitting functions out of window.c; create aiwin.c
Some checks failed
CI Code / Check coding style (pull_request) Failing after 34s
CI Code / Check spelling (pull_request) Successful in 22s
CI Code / Linux (arch) (pull_request) Failing after 2m57s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m16s
CI Code / Linux (debian) (pull_request) Failing after 6m16s
CI Code / Code Coverage (pull_request) Successful in 7m12s
2026-04-30 18:01:24 +00:00
9c8ad57b59 ref(ai): add stub, fix includes, move aiwin_send_message location
Some checks failed
CI Code / Check spelling (pull_request) Successful in 22s
CI Code / Check coding style (pull_request) Successful in 34s
CI Code / Linux (debian) (pull_request) Failing after 2m57s
CI Code / Linux (ubuntu) (pull_request) Failing after 3m9s
CI Code / Linux (arch) (pull_request) Failing after 3m13s
CI Code / Code Coverage (pull_request) Successful in 2m54s
2026-04-30 17:41:36 +00:00
1f1770bd58 fix(ai): set correct links in tests, fix headers 2026-04-30 17:02:54 +00:00
e43e8378b0 feat(ai): add AI client with multi-provider support and UI
Some checks failed
CI Code / Check coding style (pull_request) Successful in 47s
CI Code / Check spelling (pull_request) Successful in 59s
CI Code / Code Coverage (pull_request) Failing after 1m8s
CI Code / Linux (debian) (pull_request) Failing after 2m28s
CI Code / Linux (ubuntu) (pull_request) Failing after 2m41s
CI Code / Linux (arch) (pull_request) Failing after 3m15s
Add an AI client module that integrates with OpenAI-compatible API
providers (OpenAI, Perplexity, and custom providers) to provide
AI-assisted responses within the profanity client.

The implementation includes:

- src/ai/ai_client.c/h: Core AI client with provider management,
  session handling, and async HTTP request handling via libcurl.
  Supports per-provider API keys stored in preferences, reference-
  counted sessions, and conversation history tracking.

- src/ui/window.c/window_list.c: New AI window type (ProfAiWin) for
  displaying AI conversations, with response streaming and error
  display capabilities.

- Command integration: New `/ai` command (cmd_defs.c, cmd_funcs.c)
  for creating sessions, sending prompts, and managing providers.
  Provider autocomplete support in cmd_ac.c.

- Preferences integration: API keys for providers are persisted in
  the preferences system (config/preferences.c).

- Unit tests: 472 lines of comprehensive tests covering provider
  management, session lifecycle, JSON escaping, and autocomplete
  (tests/unittests/test_ai_client.c).

Architecture decisions:
- Asynchronous design: HTTP requests run on a separate thread to
  avoid blocking the main UI loop. Callbacks are invoked on the main
  thread via direct function call (profanity uses ncurses, not GLib
  main loop).
- Reference counting: Both AIProvider and AISession use ref counting
  for safe shared ownership.
- Response size limit: 10MB cap on HTTP responses to prevent OOM.
2026-04-29 19:23:33 +00:00
0feacbc9da ci: simulate Pikaur flag duplication in Arch Linux CI
All checks were successful
CI Code / Check spelling (pull_request) Successful in 17s
CI Code / Check coding style (pull_request) Successful in 30s
CI Code / Code Coverage (pull_request) Successful in 3m1s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m31s
CI Code / Linux (debian) (pull_request) Successful in 7m36s
CI Code / Linux (arch) (pull_request) Successful in 9m52s
CI Code / Check spelling (push) Successful in 18s
CI Code / Check coding style (push) Successful in 32s
CI Code / Linux (debian) (push) Successful in 4m51s
CI Code / Linux (arch) (push) Successful in 5m35s
CI Code / Linux (ubuntu) (push) Successful in 6m36s
CI Code / Code Coverage (push) Successful in 7m21s
Inject system flags from /etc/makepkg.conf into the CI environment to
detect build collisions caused by Pikaur's configuration bug.

Pikaur's cascading logic causes flags from /etc/makepkg.conf to be
merged into the build environment. This creates collisions with flags
defined in the project's Makefile.am (e.g., duplicate -D_FORTIFY_SOURCE
definitions), which can cause builds to fail for users.

By exporting these flags in the CI environment, we ensure that any
code change that is sensitive to flag duplication will trigger a
failure in our Arch Linux CI matrix, preventing broken builds from
reaching users.

Implementation details:
- Detects Arch Linux via /etc/os-release.
- Uses a sed-based flattener to handle multi-line variables and
  trailing backslashes in makepkg.conf.
- Exports the flags to the shell environment so that 'configure'
  and 'make' inherit them naturally, maintaining parity with a
  real Pikaur session.
2026-04-21 10:17:44 +00:00
0722dc9e36 build(pikaur): Fix failure due to duplicated flag and warnings
All checks were successful
CI Code / Check spelling (pull_request) Successful in 20s
CI Code / Check coding style (pull_request) Successful in 35s
CI Code / Linux (ubuntu) (pull_request) Successful in 6m42s
CI Code / Linux (debian) (pull_request) Successful in 6m47s
CI Code / Code Coverage (pull_request) Successful in 7m3s
CI Code / Linux (arch) (pull_request) Successful in 9m33s
CI Code / Check spelling (push) Successful in 20s
CI Code / Check coding style (push) Successful in 39s
CI Code / Code Coverage (push) Successful in 2m53s
CI Code / Linux (debian) (push) Successful in 4m8s
CI Code / Linux (ubuntu) (push) Successful in 4m35s
CI Code / Linux (arch) (push) Successful in 10m28s
2026-04-13 19:52:24 +00:00
30 changed files with 2718 additions and 12 deletions

View File

@@ -41,6 +41,7 @@ RUN pacman -S --needed --noconfirm \
python \
wget \
sqlite \
json-glib \
valgrind \
gdk-pixbuf2 \
qrencode

View File

@@ -35,6 +35,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
python-dev-is-python3 \
valgrind \
libsqlite3-dev \
libjson-glib-dev \
libgdk-pixbuf-2.0-dev \
libqrencode-dev

View File

@@ -38,6 +38,7 @@ RUN dnf install -y \
readline-devel \
openssl-devel \
sqlite-devel \
json-glib-devel \
valgrind \
gdk-pixbuf2-devel \
qrencode-devel

View File

@@ -37,6 +37,7 @@ RUN zypper --non-interactive in --no-recommends \
python310-devel \
readline-devel \
sqlite3-devel \
json-glib-devel \
valgrind \
gdk-pixbuf-devel \
qrencode-devel

View File

@@ -34,6 +34,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
python-dev-is-python3 \
valgrind \
libsqlite3-dev \
libjson-glib-dev \
libgdk-pixbuf-2.0-dev \
libqrencode-dev

View File

@@ -33,6 +33,7 @@ core_sources = \
src/ui/window_list.c src/ui/window_list.h \
src/ui/rosterwin.c src/ui/occupantswin.c \
src/ui/buffer.c src/ui/buffer.h \
src/ui/aiwin.c \
src/ui/chatwin.c \
src/ui/mucwin.c \
src/ui/privwin.c \
@@ -74,7 +75,8 @@ core_sources = \
src/plugins/themes.c src/plugins/themes.h \
src/plugins/settings.c src/plugins/settings.h \
src/plugins/disco.c src/plugins/disco.h \
src/ui/tray.h src/ui/tray.c
src/ui/tray.h src/ui/tray.c \
src/ai/ai_client.h src/ai/ai_client.c
unittest_sources = \
src/xmpp/contact.c src/xmpp/contact.h src/common.c \
@@ -85,6 +87,7 @@ unittest_sources = \
src/xmpp/chat_state.h src/xmpp/chat_state.c \
src/xmpp/roster_list.c src/xmpp/roster_list.h \
src/xmpp/xmpp.h src/xmpp/form.c \
src/ai/ai_client.h src/ai/ai_client.c \
src/ui/ui.h \
src/otr/otr.h \
src/pgp/gpg.h \
@@ -132,6 +135,7 @@ unittest_sources = \
tests/unittests/xmpp/stub_message.c \
tests/unittests/ui/stub_ui.c tests/unittests/ui/stub_ui.h \
tests/unittests/ui/stub_vcardwin.c \
tests/unittests/ui/stub_ai.c \
tests/unittests/log/stub_log.c \
tests/unittests/chatlog/stub_chatlog.c \
tests/unittests/database/stub_database.c \
@@ -168,6 +172,7 @@ unittest_sources = \
tests/unittests/test_callbacks.c tests/unittests/test_callbacks.h \
tests/unittests/test_plugins_disco.c tests/unittests/test_plugins_disco.h \
tests/unittests/test_forced_encryption.c tests/unittests/test_forced_encryption.h \
tests/unittests/test_ai_client.c tests/unittests/test_ai_client.h \
tests/unittests/unittests.c
functionaltest_sources = \
@@ -291,7 +296,7 @@ TESTS = tests/unittests/unittests
check_PROGRAMS = tests/unittests/unittests
tests_unittests_unittests_CPPFLAGS = -I$(srcdir)/tests
tests_unittests_unittests_SOURCES = $(unittest_sources)
tests_unittests_unittests_LDADD = -lcmocka
tests_unittests_unittests_LDADD = -lcmocka $(json-glib_LIBS)
# Functional tests require libstabber.
# They are only built when libstabber is available.

View File

@@ -204,6 +204,13 @@ case "$ARCH" in
""
)
source /etc/profile.d/debuginfod.sh 2>/dev/null || true
if grep -q 'ID=arch' /etc/os-release 2>/dev/null && [ -f /etc/makepkg.conf ]; then
echo "--> [Parity Mode] Simulating Pikaur collision..."
set -a
source /etc/makepkg.conf
set +a
fi
;;
darwin*)
# 4 configurations for parallel CI

View File

@@ -97,6 +97,10 @@ PKG_CHECK_MODULES([curl], [libcurl >= 7.62.0], [],
PKG_CHECK_MODULES([SQLITE], [sqlite3 >= 3.22.0], [],
[AC_MSG_ERROR([sqlite3 3.22.0 or higher is required])])
## Check for json-glib (JSON parsing for AI responses)
PKG_CHECK_MODULES([json-glib], [json-glib-1.0 >= 1.6.0], [],
[AC_MSG_ERROR([json-glib 1.6.0 or higher is required])])
ACX_PTHREAD([], [AC_MSG_ERROR([pthread is required])])
AS_IF([test "x$PTHREAD_CC" != x], [ CC="$PTHREAD_CC" ])
@@ -387,12 +391,11 @@ AC_SUBST([FORKPTY_LIB])
## Default parameters
AM_CFLAGS="$AM_CFLAGS -Wall -Wextra -Wformat=2 -Wno-format-zero-length"
AM_CFLAGS="$AM_CFLAGS -Wno-deprecated-declarations -Wno-unused-parameter -Wno-missing-field-initializers -Wno-sign-compare -Wno-cast-function-type"
AM_CFLAGS="$AM_CFLAGS -Wnull-dereference -Wpointer-arith"
AM_CFLAGS="$AM_CFLAGS -Wpointer-arith"
AM_CFLAGS="$AM_CFLAGS -Wimplicit-function-declaration"
AM_CFLAGS="$AM_CFLAGS -Wundef"
AM_CFLAGS="$AM_CFLAGS -Wfloat-equal -Wredundant-decls"
AM_CFLAGS="$AM_CFLAGS -fstack-protector-strong -fno-common"
AM_CFLAGS="$AM_CFLAGS -D_FORTIFY_SOURCE=2"
AM_CFLAGS="$AM_CFLAGS -std=gnu99 -ggdb3"
# GCC-specific warnings (not supported by clang) — test each one
@@ -430,11 +433,11 @@ AS_IF([test "x$PACKAGE_STATUS" = xdevelopment],
AS_IF([test "x$PLATFORM" = xosx],
[AM_CFLAGS="$AM_CFLAGS -Qunused-arguments"])
AM_CFLAGS="$AM_CFLAGS $PTHREAD_CFLAGS $glib_CFLAGS $gio_CFLAGS $curl_CFLAGS ${SQLITE_CFLAGS}"
AM_CFLAGS="$AM_CFLAGS $PTHREAD_CFLAGS $glib_CFLAGS $gio_CFLAGS $curl_CFLAGS ${SQLITE_CFLAGS} $json_glib_CFLAGS"
AM_CFLAGS="$AM_CFLAGS $libnotify_CFLAGS ${GTK_CFLAGS} $python_CFLAGS"
AM_CFLAGS="$AM_CFLAGS -DTHEMES_PATH=\"\\\"$THEMES_PATH\\\"\" -DICONS_PATH=\"\\\"$ICONS_PATH\\\"\" -DGLOBAL_PYTHON_PLUGINS_PATH=\"\\\"$GLOBAL_PYTHON_PLUGINS_PATH\\\"\" -DGLOBAL_C_PLUGINS_PATH=\"\\\"$GLOBAL_C_PLUGINS_PATH\\\"\""
LIBS="$glib_LIBS $gio_LIBS $PTHREAD_LIBS $curl_LIBS $libnotify_LIBS $python_LIBS ${GTK_LIBS} ${SQLITE_LIBS} $LIBS"
LIBS="$glib_LIBS $gio_LIBS $PTHREAD_LIBS $curl_LIBS $libnotify_LIBS $python_LIBS ${GTK_LIBS} ${SQLITE_LIBS} $json_glib_LIBS $LIBS"
AC_SUBST(AM_LDFLAGS)
AC_SUBST(AM_CFLAGS)

View File

@@ -0,0 +1,314 @@
# JSON-GLib Integration Plan for Issue #15
## Overview
This document outlines the complete plan for integrating json-glib into the CProof (profanity) build system and codebase. The integration replaces the `strstr`-based JSON parsing in [`_parse_ai_response()`](src/ai/ai_client.c:587) with proper json-glib parsing, and adds comprehensive unit tests.
---
## Current State Analysis
### What Has Already Been Done
| Component | Status | Details |
|-----------|--------|---------|
| `configure.ac` | DONE | `PKG_CHECK_MODULES([json-glib], [json-glib-1.0 >= 1.6.0])` added at line 101-102 |
| `src/ai/ai_client.c` | DONE | `#include <json-glib/json-glib.h>` added at line 24; [`_parse_ai_response()`](src/ai/ai_client.c:587) rewritten using json-glib |
| `Dockerfile.ubuntu` | DONE | `libjson-glib-dev` added at line 37 |
| `Dockerfile.debian` | DONE | `libjson-glib-dev` added at line 38 |
### What Is Missing (Root Causes of `bootstrap.sh` Failure)
1. **`Makefile.am` missing json-glib flags:**
- `AM_CFLAGS` at line 272 does not include `$(json-glib_CFLAGS)`
- `tests_unittests_unittests_LDADD` at line 299 does not include `$(json-glib_LIBS)`
- The main `profanity` binary target also needs `$(json-glib_LIBS)` in its link flags
2. **No unit tests for `_parse_ai_response()`:**
- [`test_ai_client.c`](tests/unittests/test_ai_client.c) has 464 lines of tests but none for the JSON parsing function
- The function is `static`, so it cannot be tested directly; a test harness or refactoring is needed
3. **`bootstrap.sh` failure:**
- [`bootstrap.sh`](bootstrap.sh) is a simple script: `mkdir -p m4 && autoreconf -i "$@"`
- The failure is caused by `autoreconf` failing due to missing json-glib m4 macros in the `m4/` directory, or the `configure.ac` referencing `PKG_CHECK_MODULES` without the proper `ax_pthread.m4` or json-glib pkg-config files being available in the build environment
---
## Detailed Plan
### 1. Build System Changes
#### 1.1 `configure.ac` — No Changes Needed
The json-glib check is already present:
```autoconf
PKG_CHECK_MODULES([json-glib], [json-glib-1.0 >= 1.6.0], [],
[AC_MSG_ERROR([json-glib 1.6.0 or higher is required])])
```
This generates the variables `json-glib_CFLAGS` and `json-glib_LIBS` for use in `Makefile.am`.
#### 1.2 `Makefile.am` — Changes Required
**File:** [`Makefile.am`](Makefile.am)
**Change 1: Add json-glib_CFLAGS to AM_CFLAGS (line 272)**
```makefile
# Current (line 272):
AM_CFLAGS = @AM_CFLAGS@ -I$(srcdir)/src
# Change to:
AM_CFLAGS = @AM_CFLAGS@ $(json-glib_CFLAGS) -I$(srcdir)/src
```
**Change 2: Add json-glib_LIBS to profanity linking (line 275)**
The `profanity` binary target needs json-glib_LIBS. Since `profanity_SOURCES` is defined at line 275 and no explicit `profanity_LDADD` exists, we need to add one:
```makefile
# Add after line 275:
profanity_LDADD = $(json-glib_LIBS) $(LIBS)
```
**Change 3: Add json-glib_LIBS to test linking (line 299)**
```makefile
# Current (line 299):
tests_unittests_unittests_LDADD = -lcmocka
# Change to:
tests_unittests_unittests_LDADD = -lcmocka $(json-glib_LIBS)
```
#### 1.3 Why `bootstrap.sh` Fails
The [`bootstrap.sh`](bootstrap.sh) script runs `autoreconf -i`, which regenerates the `configure` script from `configure.ac`. The failure occurs because:
1. **pkg-config dependency:** `PKG_CHECK_MODULES` requires `pkg-config` to be available at configure-time (not build-time). The `autoreconf` step itself should succeed, but the resulting `configure` script will fail if `pkg-config --modversion json-glib-1.0 >= 1.6.0` cannot find the json-glib installation.
2. **Likely root cause:** The build environment (Docker container or host) does not have `json-glib` development files installed, or `pkg-config` cannot locate the `json-glib-1.0.pc` file.
**Fix:** Ensure `libjson-glib-dev` (Debian/Ubuntu) or `json-glib` (Arch/Fedora) is installed in the build environment before running `bootstrap.sh`.
---
### 2. Source Code Changes
#### 2.1 `src/ai/ai_client.c` — No Changes Needed
The [`_parse_ai_response()`](src/ai/ai_client.c:587) function has already been rewritten using json-glib:
```c
static gchar*
_parse_ai_response(const gchar* response_json)
{
// ... json-glib parsing with three fallback strategies:
// Try 1: Perplexity /v1/agent format
// Try 2: OpenAI /v1/chat/completions format
// Try 3: Fallback "text" field
}
```
#### 2.2 `src/ai/ai_client.h` — No Changes Needed
The header file already includes `<glib.h>` and defines all necessary types. No json-glib-specific types are exposed (json-glib is an implementation detail).
---
### 3. Test Changes
#### 3.1 `tests/unittests/test_ai_client.c` — New Tests Required
The current test file has 464 lines covering provider management, session handling, JSON escaping, and autocomplete. **No tests exist for `_parse_ai_response()`** because it is `static`.
**Option A: Refactor `_parse_ai_response` to be testable (Recommended)**
Make the function non-static and add a test wrapper:
```c
// In ai_client.h, add:
gchar* ai_parse_ai_response(const gchar* response_json);
// In ai_client.c, change:
// static gchar* _parse_ai_response(...) → gchar* ai_parse_ai_response(...)
```
**Option B: Use a test harness with `extern` declaration**
Add to test file:
```c
extern gchar* _parse_ai_response(const gchar* response_json);
```
**Recommended tests to add:**
| Test Name | Description |
|-----------|-------------|
| `test_ai_parse_response_null` | NULL input returns NULL |
| `test_ai_parse_response_empty` | Empty string returns NULL |
| `test_ai_parse_response_invalid_json` | Malformed JSON returns NULL |
| `test_ai_parse_response_openai_format` | Valid OpenAI `/v1/chat/completions` response |
| `test_ai_parse_response_openai_empty_choices` | Response with empty choices array |
| `test_ai_parse_response_perplexity_format` | Valid Perplexity `/v1/agent` response |
| `test_ai_parse_response_perplexity_empty_output` | Response with empty output array |
| `test_ai_parse_response_text_fallback` | Response with only "text" field |
| `test_ai_parse_response_unicode_content` | Content with unicode characters |
| `test_ai_parse_response_multiline_content` | Content with newlines and tabs |
| `test_ai_parse_response_html_content` | Content with HTML tags |
| `test_ai_parse_response_error_format` | Response with "error" field (not "choices") |
#### 3.2 `tests/unittests/test_ai_client.h` — Update Required
Add declarations for new test functions:
```c
/* JSON parsing tests */
void test_ai_parse_response_null(void** state);
void test_ai_parse_response_empty(void** state);
void test_ai_parse_response_invalid_json(void** state);
void test_ai_parse_response_openai_format(void** state);
void test_ai_parse_response_openai_empty_choices(void** state);
void test_ai_parse_response_perplexity_format(void** state);
void test_ai_parse_response_perplexity_empty_output(void** state);
void test_ai_parse_response_text_fallback(void** state);
void test_ai_parse_response_unicode_content(void** state);
void test_ai_parse_response_multiline_content(void** state);
void test_ai_parse_response_html_content(void** state);
void test_ai_parse_response_error_format(void** state);
```
#### 3.3 `tests/unittests/unittests.c` — Update Required
Add new test entries after the existing AI client tests (around line 696):
```c
// After line 696 (test_ai_json_escape_backslash_quote):
cmocka_unit_test(test_ai_parse_response_null),
cmocka_unit_test(test_ai_parse_response_empty),
cmocka_unit_test(test_ai_parse_response_invalid_json),
cmocka_unit_test(test_ai_parse_response_openai_format),
cmocka_unit_test(test_ai_parse_response_openai_empty_choices),
cmocka_unit_test(test_ai_parse_response_perplexity_format),
cmocka_unit_test(test_ai_parse_response_perplexity_empty_output),
cmocka_unit_test(test_ai_parse_response_text_fallback),
cmocka_unit_test(test_ai_parse_response_unicode_content),
cmocka_unit_test(test_ai_parse_response_multiline_content),
cmocka_unit_test(test_ai_parse_response_html_content),
cmocka_unit_test(test_ai_parse_response_error_format),
```
---
### 4. Dockerfile Changes
#### 4.1 `Dockerfile.ubuntu` — No Changes Needed
`libjson-glib-dev` is already present at line 37.
#### 4.2 `Dockerfile.debian` — No Changes Needed
`libjson-glib-dev` is already present at line 38.
#### 4.3 `Dockerfile.fedora` — Check Required
Verify `json-glib-devel` is installed. If not, add:
```dockerfile
json-glib-devel \
```
#### 4.4 `Dockerfile.arch` — Check Required
Verify `json-glib` is installed. If not, add:
```dockerfile
json-glib \
```
---
### 5. Bootstrap.sh Fix
#### 5.1 Current State
[`bootstrap.sh`](bootstrap.sh):
```sh
#!/bin/sh
mkdir -p m4
autoreconf -i "$@"
```
#### 5.2 Root Cause Analysis
The script itself is correct. The failure is due to one of:
1. **Missing `json-glib-1.0.pc`**: `pkg-config` cannot find json-glib in the build environment
2. **Missing `m4/ax_pthread.m4`**: The `configure.ac` uses `ACX_PTHREAD` which requires the `ax_pthread.m4` macro
3. **Missing `m4/` macros**: Other autoconf macros referenced in `configure.ac` are not present
#### 5.3 Fix Steps
1. **Ensure json-glib-dev is installed** in the build environment
2. **Verify m4 macros exist:**
```bash
ls -la m4/
# Should contain: ax_pthread.m4, ax_valgrind_check.m4, etc.
```
3. **If m4 macros are missing**, they need to be copied from the system:
```bash
# For Debian/Ubuntu:
cp /usr/share/autoconf-archive/m4/ax_pthread.m4 m4/
cp /usr/share/autoconf-archive/m4/ax_valgrind_check.m4 m4/
```
4. **Test bootstrap.sh manually:**
```bash
./bootstrap.sh
./configure
make
```
---
## Implementation Order
```mermaid
graph TD
A[1. Fix Makefile.am] --> B[2. Verify bootstrap.sh works]
B --> C[3. Add test functions to test_ai_client.c]
C --> D[4. Update test_ai_client.h]
D --> E[5. Register tests in unittests.c]
E --> F[6. Verify Dockerfiles have json-glib-dev]
F --> G[7. Run make check to verify all tests pass]
```
---
## Summary of Changes
| File | Change Type | Lines Affected |
|------|-------------|----------------|
| `Makefile.am` | Modify | Line 272 (AM_CFLAGS), Line 275 (add profanity_LDADD), Line 299 (LDADD) |
| `src/ai/ai_client.c` | None | Already complete |
| `src/ai/ai_client.h` | None | Already complete |
| `tests/unittests/test_ai_client.c` | Add | ~200 lines of new test functions |
| `tests/unittests/test_ai_client.h` | Add | ~12 new declarations |
| `tests/unittests/unittests.c` | Add | ~12 new test entries |
| `Dockerfile.ubuntu` | None | Already has libjson-glib-dev |
| `Dockerfile.debian` | None | Already has libjson-glib-dev |
| `Dockerfile.fedora` | Check | Verify json-glib-devel present |
| `Dockerfile.arch` | Check | Verify json-glib present |
| `bootstrap.sh` | Diagnose | Fix is environmental, not script change |
---
## Verification Checklist
- [ ] `Makefile.am` updated with `$(json-glib_CFLAGS)` and `$(json-glib_LIBS)`
- [ ] `bootstrap.sh` runs successfully
- [ ] `./configure` completes without json-glib errors
- [ ] `make` compiles without errors
- [ ] `make check` runs all tests including new json-glib tests
- [ ] All existing tests still pass
- [ ] Docker builds succeed with json-glib integration

839
src/ai/ai_client.c Normal file
View File

@@ -0,0 +1,839 @@
/*
* ai_client.c - AI client for interacting with OpenAI-compatible API providers
*
* Supports multiple providers (OpenAI, Perplexity, etc.) with per-provider
* API keys, custom endpoints, and model selection.
*
* Copyright (C) 2026 CProof Developers
*
* SPDX-License-Identifier: GPL-3.0-or-later WITH OpenSSL-exception
*/
// vim: expandtab:ts=4:sts=4:sw=4
#include "ai_client.h"
#include "common.h"
#include "log.h"
#include "config/preferences.h"
#include "profanity.h"
#include "tools/autocomplete.h"
#include "ui/ui.h"
#include "ui/window_list.h"
#include <curl/curl.h>
#include <glib.h>
#include <json-glib/json-glib.h>
#include <string.h>
/* Default providers */
#define DEFAULT_OPENAI_URL "https://api.openai.com/"
#define DEFAULT_PERPLEXITY_URL "https://api.perplexity.ai/"
/* Global state */
static GHashTable* providers = NULL;
static GHashTable* provider_keys = NULL;
static Autocomplete providers_ac = NULL;
/* ========================================================================
* Curl helpers
* ======================================================================== */
struct curl_response_t
{
gchar* data;
size_t size;
};
static size_t
_write_callback(void* ptr, size_t size, size_t nmemb, void* userdata)
{
size_t realsize = size * nmemb;
struct curl_response_t* res = (struct curl_response_t*)userdata;
/* Limit response size to 10MB to prevent OOM */
if (res->size + realsize > 10 * 1024 * 1024) {
log_error("[AI-THREAD] Response too large, truncating");
return realsize;
}
gchar* new_data = g_realloc(res->data, res->size + realsize + 1);
if (!new_data) {
log_error("[AI-THREAD] Failed to allocate memory for response");
return realsize;
}
res->data = new_data;
memcpy(res->data + res->size, ptr, realsize);
res->size += realsize;
res->data[res->size] = '\0';
return realsize;
}
/* ========================================================================
* Thread-safe UI display helpers
* ======================================================================== */
/**
* Validate aiwin pointer by checking if it still exists in the window list.
* Detects if the original window was freed (TOCTOU protection).
* Returns the validated pointer if valid, NULL if window was closed.
*/
static ProfAiWin*
_aiwin_validate(gpointer user_data)
{
if (!user_data) {
return NULL;
}
if (!wins_ai_exists((ProfAiWin*)user_data)) {
log_warning("[AI-THREAD] aiwin=%p no longer exists — window was closed", (void*)user_data);
return NULL;
}
/* Pointer is valid */
return (ProfAiWin*)user_data;
}
/**
* Display an error message in the AI window (thread-safe).
* @param user_data The original user_data pointer (may be NULL)
* @param error_msg The error message to display
*/
static void
_aiwin_display_error(gpointer user_data, const gchar* error_msg)
{
ProfAiWin* aiwin = _aiwin_validate(user_data);
if (!aiwin) {
log_warning("[AI-THREAD] Cannot display error: aiwin is invalid or window was closed (msg: %s)", error_msg);
return;
}
pthread_mutex_lock(&lock);
aiwin_display_error(aiwin, error_msg);
pthread_mutex_unlock(&lock);
}
/**
* Display a response message in the AI window (thread-safe).
* @param user_data The original user_data pointer (may be NULL)
* @param response The response message to display
*/
static void
_aiwin_display_response(gpointer user_data, const gchar* response)
{
ProfAiWin* aiwin = _aiwin_validate(user_data);
if (!aiwin) {
log_warning("[AI-THREAD] Cannot display response: aiwin is invalid or window was closed");
return;
}
pthread_mutex_lock(&lock);
aiwin_display_response(aiwin, response);
pthread_mutex_unlock(&lock);
}
/* ========================================================================
* JSON helpers
* ======================================================================== */
gchar*
ai_json_escape(const gchar* str)
{
if (!str)
return g_strdup("");
GString* result = g_string_new("");
for (const gchar* p = str; *p; p++) {
switch (*p) {
case '"':
g_string_append(result, "\\\"");
break;
case '\\':
g_string_append(result, "\\\\");
break;
case '\b':
g_string_append(result, "\\b");
break;
case '\f':
g_string_append(result, "\\f");
break;
case '\n':
g_string_append(result, "\\n");
break;
case '\r':
g_string_append(result, "\\r");
break;
case '\t':
g_string_append(result, "\\t");
break;
default:
g_string_append_c(result, *p);
break;
}
}
return g_string_free(result, FALSE);
}
/* ========================================================================
* Provider Management
* ======================================================================== */
static AIProvider*
ai_provider_new(const gchar* name, const gchar* api_url, const gchar* org_id)
{
AIProvider* provider = g_new0(AIProvider, 1);
provider->name = g_strdup(name);
provider->api_url = g_strdup(api_url ? api_url : "");
provider->org_id = g_strdup(org_id);
provider->project_id = NULL;
provider->models = NULL;
provider->ref_count = 1;
return provider;
}
static AIProvider*
ai_provider_ref(AIProvider* provider)
{
if (provider) {
g_atomic_int_inc(&provider->ref_count);
}
return provider;
}
void
ai_provider_unref(AIProvider* provider)
{
if (!provider)
return;
if (!g_atomic_int_dec_and_test(&provider->ref_count)) {
return;
}
g_free(provider->name);
g_free(provider->api_url);
g_free(provider->org_id);
g_free(provider->project_id);
GList* curr = provider->models;
while (curr) {
g_free(curr->data);
curr = g_list_next(curr);
}
g_list_free(provider->models);
g_free(provider);
}
static void
ai_load_keys(void)
{
if (!provider_keys) {
provider_keys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
}
GList* tokens = prefs_ai_list_tokens();
if (!tokens) {
return;
}
GList* curr = tokens;
while (curr) {
gchar* provider = (gchar*)curr->data;
gchar* key = prefs_ai_get_token(provider);
if (key && strlen(key) > 0) {
g_hash_table_insert(provider_keys, g_strdup(provider), g_strdup(key));
}
g_free(key);
curr = g_list_next(curr);
}
prefs_free_ai_tokens(tokens);
log_info("Loaded %d saved API keys from config", g_hash_table_size(provider_keys));
}
void
ai_client_init(void)
{
if (providers)
return; /* Already initialized */
curl_global_init(CURL_GLOBAL_ALL);
/* Create hash tables */
providers = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify)ai_provider_unref);
provider_keys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
/* Create autocomplete for provider names */
providers_ac = autocomplete_new();
/* Add default providers */
ai_add_provider("openai", DEFAULT_OPENAI_URL, NULL);
ai_add_provider("perplexity", DEFAULT_PERPLEXITY_URL, NULL);
/* Load saved API keys from config */
ai_load_keys();
log_info("AI client initialized with default providers: openai, perplexity");
}
void
ai_client_shutdown(void)
{
if (!providers)
return;
g_hash_table_destroy(providers);
g_hash_table_destroy(provider_keys);
providers = NULL;
provider_keys = NULL;
if (providers_ac) {
autocomplete_free(providers_ac);
providers_ac = NULL;
}
curl_global_cleanup();
log_info("AI client shutdown");
}
AIProvider*
ai_get_provider(const gchar* name)
{
if (!name || !providers)
return NULL;
return g_hash_table_lookup(providers, name);
}
AIProvider*
ai_add_provider(const gchar* name, const gchar* api_url, const gchar* org_id)
{
if (!name || !api_url)
return NULL;
if (!providers) {
ai_client_init();
}
/* Check if provider already exists */
AIProvider* existing = g_hash_table_lookup(providers, name);
if (existing) {
/* Update existing provider */
g_free(existing->api_url);
existing->api_url = g_strdup(api_url);
g_free(existing->org_id);
existing->org_id = g_strdup(org_id);
log_info("Updated provider: %s", name);
return ai_provider_ref(existing);
}
/* Create new provider (ref_count=1 owned by hash table) */
AIProvider* provider = ai_provider_new(name, api_url, org_id);
g_hash_table_insert(providers, g_strdup(name), provider);
/* Sync autocomplete */
autocomplete_add(providers_ac, name);
log_info("Added provider: %s (URL: %s)", name, api_url);
return provider; /* Caller gets non-owning pointer; hash table owns ref */
}
gboolean
ai_remove_provider(const gchar* name)
{
if (!name || !providers)
return FALSE;
/* Sync autocomplete before removing */
autocomplete_remove(providers_ac, name);
return g_hash_table_remove(providers, name);
}
GList*
ai_list_providers(void)
{
if (!providers)
return NULL;
GList* result = NULL;
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, providers);
while (g_hash_table_iter_next(&iter, &key, &value)) {
result = g_list_append(result, value);
}
return result;
}
/* ========================================================================
* Provider autocomplete state
* ======================================================================== */
/* Stateful provider name finder with case-sensitive matching.
* Maintains position in sorted list for deterministic tab-completion cycling.
* The autocomplete is kept in sync via ai_add_provider/ai_remove_provider. */
gchar*
ai_providers_find(const char* const search_str, gboolean previous, void* context)
{
/* Initialize autocomplete on first use */
if (!providers_ac) {
providers_ac = autocomplete_new();
}
/* NULL search_str is treated as empty string for cycling */
const char* effective_search = (search_str != NULL) ? search_str : "";
/* Use stateful autocomplete */
return autocomplete_complete(providers_ac, effective_search, FALSE, previous);
}
gchar*
ai_get_provider_key(const gchar* provider_name)
{
if (!provider_name || !provider_keys)
return NULL;
gchar* key = g_hash_table_lookup(provider_keys, provider_name);
return g_strdup(key);
}
void
ai_set_provider_key(const gchar* provider_name, const gchar* api_key)
{
if (!provider_name)
return;
if (!provider_keys) {
provider_keys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
}
if (api_key) {
g_hash_table_insert(provider_keys, g_strdup(provider_name), g_strdup(api_key));
/* Persist to config file */
prefs_ai_set_token(provider_name, api_key);
log_info("API key set for provider: %s", provider_name);
} else {
g_hash_table_remove(provider_keys, provider_name);
/* Remove from config file */
prefs_ai_remove_token(provider_name);
log_info("API key removed for provider: %s", provider_name);
}
}
/* ========================================================================
* Session Management
* ======================================================================== */
AISession*
ai_session_create(const gchar* provider_name, const gchar* model)
{
if (!provider_name || !model)
return NULL;
AIProvider* provider = ai_get_provider(provider_name);
if (!provider) {
log_error("Provider not found: %s", provider_name);
return NULL;
}
AISession* session = g_new0(AISession, 1);
session->provider_name = g_strdup(provider_name);
session->provider = ai_provider_ref(provider);
session->model = g_strdup(model);
session->api_key = ai_get_provider_key(provider_name);
session->history = NULL;
session->ref_count = 1;
log_info("AI session created: %s/%s", provider_name, model);
return session;
}
AISession*
ai_session_ref(AISession* session)
{
if (session) {
g_atomic_int_inc(&session->ref_count);
}
return session;
}
void
ai_session_unref(AISession* session)
{
if (!session)
return;
if (!g_atomic_int_dec_and_test(&session->ref_count)) {
return;
}
g_free(session->provider_name);
ai_provider_unref(session->provider);
g_free(session->model);
g_free(session->api_key);
GList* curr = session->history;
while (curr) {
AIMessage* msg = curr->data;
g_free(msg->role);
g_free(msg->content);
g_free(msg);
curr = g_list_next(curr);
}
g_list_free(session->history);
g_free(session);
log_debug("AI session destroyed");
}
void
ai_session_add_message(AISession* session, const gchar* role, const gchar* content)
{
if (!session || !role || !content)
return;
AIMessage* msg = g_new0(AIMessage, 1);
msg->role = g_strdup(role);
msg->content = g_strdup(content);
session->history = g_list_append(session->history, msg);
log_debug("Added %s message to session (total: %d)", role, g_list_length(session->history));
}
void
ai_session_clear_history(AISession* session)
{
if (!session)
return;
GList* curr = session->history;
while (curr) {
AIMessage* msg = curr->data;
g_free(msg->role);
g_free(msg->content);
g_free(msg);
curr = g_list_next(curr);
}
g_list_free(session->history);
session->history = NULL;
log_info("AI session history cleared");
}
const gchar*
ai_session_get_model(AISession* session)
{
if (!session)
return NULL;
return session->model;
}
void
ai_session_set_model(AISession* session, const gchar* model)
{
if (!session || !model)
return;
g_free(session->model);
session->model = g_strdup(model);
log_info("Session model changed to: %s", model);
}
/* ========================================================================
* API Request Handling
* ======================================================================== */
static gchar*
_build_json_payload(AISession* session, const gchar* prompt)
{
/* OpenAI-compatible Responses API format:
* {"model": "...", "input": [...], "stream": false, "store": false}
* store:false prevents providers from storing/using requests for training */
GString* messages_json = g_string_new("");
GList* curr = session->history;
while (curr) {
AIMessage* msg = curr->data;
auto_gchar gchar* escaped_content = ai_json_escape(msg->content);
auto_gchar gchar* escaped_role = ai_json_escape(msg->role);
if (messages_json->len > 0) {
g_string_append_c(messages_json, ',');
}
g_string_append_printf(messages_json, "{\"role\":\"%s\",\"content\":\"%s\"}",
escaped_role, escaped_content);
curr = g_list_next(curr);
}
/* Add the new user message */
auto_gchar gchar* escaped_prompt = ai_json_escape(prompt);
if (messages_json->len > 0) {
g_string_append_c(messages_json, ',');
}
g_string_append_printf(messages_json, "{\"role\":\"user\",\"content\":\"%s\"}", escaped_prompt);
auto_gchar gchar* escaped_model = ai_json_escape(session->model);
gchar* json_payload = g_strdup_printf(
"{\"model\":\"%s\",\"input\":[%s],\"stream\":false,\"store\":false}",
escaped_model, messages_json->str);
g_string_free(messages_json, TRUE);
return json_payload;
}
/** @brief Parse AI response JSON and extract content string.
*
* Tries multiple JSON paths to handle different provider response formats:
* 1. Perplexity /v1/agent: {"output":[{"content":[{"text":"..."}]}]}
* 2. OpenAI /v1/chat/completions: {"choices":[{"message":{"content":"..."}}]}
* 3. Fallback: root-level "text" field
* 4. Fallback: root-level "content" field
*
* @param response_json The JSON response string
* @return Newly allocated content string, or NULL on failure
*/
gchar*
ai_parse_response(const gchar* response_json)
{
if (!response_json || strlen(response_json) == 0) {
log_warning("[AI-THREAD] Empty or NULL response JSON");
return NULL;
}
/* Parse JSON using json-glib */
auto_gchar gchar* error_msg = NULL;
JsonParser* parser = json_parser_new();
if (!json_parser_load_from_data(parser, response_json, -1, &error_msg)) {
log_warning("[AI-THREAD] Failed to parse AI response JSON: %s", error_msg ? error_msg : "unknown error");
g_object_unref(parser);
return NULL;
}
JsonNode* root = json_parser_get_root(parser);
if (!root || !JSON_IS_OBJECT(json_node_get_object(root))) {
log_warning("[AI-THREAD] Invalid AI response JSON: root is not an object");
g_object_unref(parser);
return NULL;
}
JsonObject* root_obj = json_node_get_object(root);
gchar* content = NULL;
/* Try 1: Perplexity /v1/agent format
* {"output":[{"content":[{"text":"...","type":"output_text"}]}]} */
JsonNode* output_node = json_object_get_member(root_obj, "output");
if (output_node && JSON_IS_ARRAY(json_node_get_array(output_node))) {
JsonArray* output_arr = json_node_get_array(output_node);
if (json_array_get_length(output_arr) > 0) {
JsonObject* first_output = json_array_get_object_element(output_arr, 0);
JsonNode* content_node = json_object_get_member(first_output, "content");
if (content_node && JSON_IS_ARRAY(json_node_get_array(content_node))) {
JsonArray* content_arr = json_node_get_array(content_node);
if (json_array_get_length(content_arr) > 0) {
JsonObject* first_content = json_array_get_object_element(content_arr, 0);
JsonNode* text_node = json_object_get_member(first_content, "text");
if (text_node && JSON_IS_VALUE(text_node)) {
content = g_strdup(json_node_get_string(text_node));
}
}
}
}
}
/* Try 2: OpenAI /v1/chat/completions format
* {"choices":[{"message":{"content":"..."}}]} */
if (!content) {
JsonNode* choices_node = json_object_get_member(root_obj, "choices");
if (choices_node && JSON_IS_ARRAY(json_node_get_array(choices_node))) {
JsonArray* choices_arr = json_node_get_array(choices_node);
if (json_array_get_length(choices_arr) > 0) {
JsonObject* first_choice = json_array_get_object_element(choices_arr, 0);
JsonNode* message_node = json_object_get_member(first_choice, "message");
if (message_node && JSON_IS_OBJECT(json_node_get_object(message_node))) {
JsonObject* message = json_node_get_object(message_node);
JsonNode* content_member = json_object_get_member(message, "content");
if (content_member && JSON_IS_VALUE(content_member)) {
content = g_strdup(json_node_get_string(content_member));
}
}
}
}
}
/* Try 3: Fallback - look for "text" field anywhere in the response
* This handles edge cases where the response shape differs */
if (!content) {
JsonNode* text_node = json_object_get_member(root_obj, "text");
if (text_node && JSON_IS_VALUE(text_node)) {
content = g_strdup(json_node_get_string(text_node));
}
}
/* Try 4: Fallback - look for "content" field at root level */
if (!content) {
JsonNode* content_node = json_object_get_member(root_obj, "content");
if (content_node && JSON_IS_VALUE(content_node)) {
content = g_strdup(json_node_get_string(content_node));
}
}
g_object_unref(parser);
if (!content) {
log_warning("[AI-THREAD] Could not extract content from AI response");
}
return content;
}
static gpointer
_ai_request_thread(gpointer data)
{
log_debug("[AI-THREAD] Starting AI request thread");
/* Data is an array: [0]=session, [1]=prompt, [2]=user_data */
gpointer* args = (gpointer*)data;
AISession* session = (AISession*)args[0];
auto_gchar gchar* prompt = args[1];
gpointer user_data = args[2];
log_debug("[AI-THREAD] Session: %s/%s", session->provider_name, session->model);
log_debug("[AI-THREAD] API key length: %zu", session->api_key ? strlen(session->api_key) : 0);
/* Check for API key first */
if (!session->api_key || strlen(session->api_key) == 0) {
auto_gchar gchar* error_msg = g_strdup_printf("No API key set for provider '%s'. Use '/ai set token %s <key>' to configure.",
session->provider_name, session->provider_name);
log_error("AI request failed for %s/%s: %s", session->provider_name, session->model, error_msg);
_aiwin_display_error(user_data, error_msg);
g_free(args);
return NULL;
}
CURL* curl = curl_easy_init();
log_debug("[AI-THREAD] Curl initialized: %s", curl ? "OK" : "FAILED");
if (!curl) {
log_error("AI request failed for %s/%s: Failed to initialize curl",
session->provider_name, session->model);
_aiwin_display_error(user_data, "Failed to initialize curl.");
g_free(args);
return NULL;
}
/* Add user message to history FIRST */
ai_session_add_message(session, "user", prompt);
log_debug("[AI-THREAD] Added user message to history");
/* Build JSON payload (includes the message we just added) */
log_debug("[AI-THREAD] Building JSON payload...");
auto_gchar gchar* json_payload = _build_json_payload(session, prompt);
log_debug("[AI-THREAD] JSON payload: %s", json_payload);
/* Set up headers */
struct curl_slist* headers = NULL;
auto_gchar gchar* auth_header = g_strdup_printf("Authorization: Bearer %s", session->api_key);
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, auth_header);
/* Add organization header if configured */
if (session->provider && session->provider->org_id && strlen(session->provider->org_id) > 0) {
auto_gchar gchar* org_header = g_strdup_printf("OpenAI-Organization: %s", session->provider->org_id);
headers = curl_slist_append(headers, org_header);
}
/* Response buffer */
struct curl_response_t response;
response.data = g_new0(gchar, 1);
response.size = 0;
/* Configure request */
const gchar* api_url = session->provider ? session->provider->api_url : DEFAULT_OPENAI_URL;
auto_gchar gchar* request_url = g_strdup_printf("%s%sv1/responses", api_url, g_str_has_suffix(api_url, "/") ? "" : "/");
log_debug("[AI-THREAD] API URL: %s", api_url);
log_debug("[AI-THREAD] API Request URL: %s", request_url);
log_debug("[AI-THREAD] Model: %s", session->model);
curl_easy_setopt(curl, CURLOPT_URL, request_url);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_payload);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60L);
CURLcode res = curl_easy_perform(curl);
log_debug("[AI-THREAD] curl_easy_perform completed, res: %d", res);
/* Get HTTP response code */
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
log_debug("[AI-THREAD] HTTP response code: %ld", http_code);
if (res != CURLE_OK) {
auto_gchar gchar* error_msg = g_strdup(curl_easy_strerror(res));
log_error("AI request failed for %s/%s: %s", session->provider_name, session->model, error_msg);
_aiwin_display_error(user_data, error_msg);
} else if (http_code >= 400) {
/* Handle HTTP errors */
log_debug("[AI-THREAD] HTTP error response body (%zu bytes): %s",
response.size, response.data ? response.data : "NULL");
auto_gchar gchar* error_msg = g_strdup_printf("HTTP %ld: %s", http_code,
response.data ? response.data : "Unknown error");
log_error("AI request failed for %s/%s: %s", session->provider_name, session->model, error_msg);
_aiwin_display_error(user_data, error_msg);
} else {
/* Parse response - transfer ownership to auto_gchar for cleanup */
log_debug("[AI-THREAD] Raw API response (%zu bytes): %s", response.size, response.data ? response.data : "NULL");
auto_gchar gchar* response_data = response.data;
response.data = NULL;
auto_gchar gchar* content = _parse_ai_response(response_data);
if (content) {
/* Add assistant response to history */
ai_session_add_message(session, "assistant", content);
_aiwin_display_response(user_data, content);
} else {
log_error("AI response parse failed for %s/%s: %.200s...",
session->provider_name, session->model, response_data);
_aiwin_display_error(user_data, "Failed to parse AI response.");
}
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
g_free(args);
return NULL;
}
gboolean
ai_send_prompt(AISession* session, const gchar* prompt, gpointer user_data)
{
log_debug("[AI-PROMPT] ENTER: session=%p, prompt='%s', user_data=%p",
(void*)session, prompt, user_data);
if (!session || !prompt) {
log_error("[AI-PROMPT] FAIL: invalid session or prompt");
return FALSE;
}
/* Prepare thread arguments: [0]=session, [1]=prompt, [2]=user_data */
gpointer* args = g_new0(gpointer, 3);
args[0] = ai_session_ref(session);
args[1] = g_strdup(prompt);
args[2] = user_data;
log_debug("[AI-PROMPT] Prepared args, creating thread...");
GThread* thread = g_thread_new("ai_request", _ai_request_thread, args);
if (!thread) {
g_free(args[1]);
ai_session_unref(session);
g_free(args);
log_error("[AI-PROMPT] FAIL: g_thread_new returned NULL");
return FALSE;
}
log_debug("[AI-PROMPT] Thread created successfully: %p", (void*)thread);
g_thread_unref(thread);
return TRUE;
}

188
src/ai/ai_client.h Normal file
View File

@@ -0,0 +1,188 @@
#ifndef AI_CLIENT_H
#define AI_CLIENT_H
#include <glib.h>
/**
* @brief AI message structure for conversation history.
*/
typedef struct ai_message_t
{
gchar* role; /* "user" or "assistant" */
gchar* content; /* Message content */
} AIMessage;
/**
* @brief AI provider configuration.
*/
typedef struct ai_provider_t
{
gchar* name; /* Provider name (e.g., "openai", "perplexity") */
gchar* api_url; /* API endpoint URL */
gchar* org_id; /* Optional organization ID */
gchar* project_id; /* Optional project ID (for some providers) */
GList* models; /* List of available models (gchar*) */
gint32 ref_count; /* Reference count (atomic) */
} AIProvider;
/**
* @brief AI chat session structure.
*/
typedef struct ai_session_t
{
gchar* provider_name; /* Provider name */
AIProvider* provider; /* Provider configuration */
gchar* model; /* Model identifier (e.g., "gpt-4", "sonar") */
gchar* api_key; /* API key for this session */
GList* history; /* Conversation history (GList of AIMessage*) */
gint32 ref_count; /* Reference count (atomic) */
} AISession;
/* ========================================================================
* Provider Management
* ======================================================================== */
/**
* Initialize the AI client and load default providers.
*/
void ai_client_init(void);
/**
* Shutdown the AI client and free resources.
*/
void ai_client_shutdown(void);
/**
* Get a provider by name.
* @param name The provider name (e.g., "openai", "perplexity")
* @return AIProvider*, or NULL if not found
*/
AIProvider* ai_get_provider(const gchar* name);
/**
* Add or update a provider configuration.
* @param name The provider name
* @param api_url The API endpoint URL
* @param org_id Optional organization ID (can be NULL)
* @return New AIProvider* (caller must unref when done)
*/
AIProvider* ai_add_provider(const gchar* name, const gchar* api_url, const gchar* org_id);
/**
* Remove a provider by name.
* @param name The provider name
* @return TRUE if provider was removed, FALSE if not found
*/
gboolean ai_remove_provider(const gchar* name);
/**
* Decrement the reference count of a provider.
* @param provider The provider to unreference
*/
void ai_provider_unref(AIProvider* provider);
/**
* List all configured providers.
* @return GList of AIProvider* (caller must not free the list or providers,
* and must not unref the returned providers)
*/
GList* ai_list_providers(void);
/**
* Find a provider name for autocomplete.
* @param search_str The search string
* @param previous Whether to go to previous match
* @param context Unused
* @return Provider name, or NULL if not found
*/
gchar* ai_providers_find(const char* const search_str, gboolean previous, void* context);
/**
* Get the API key for a provider.
* @param provider_name The provider name
* @return The API key, or NULL if not set (caller must free)
*/
gchar* ai_get_provider_key(const gchar* provider_name);
/**
* Set the API key for a provider.
* @param provider_name The provider name
* @param api_key The API key to set
*/
void ai_set_provider_key(const gchar* provider_name, const gchar* api_key);
/* ========================================================================
* Session Management
* ======================================================================== */
/**
* Create a new AI session with the specified provider and model.
* @param provider_name The provider name (e.g., "openai")
* @param model The model identifier (e.g., "gpt-4")
* @return New AISession*, or NULL on failure
*/
AISession* ai_session_create(const gchar* provider_name, const gchar* model);
/**
* Increment the reference count of an AI session.
* @param session The session to reference
* @return The same session pointer
*/
AISession* ai_session_ref(AISession* session);
/**
* Decrement the reference count and free the session when it reaches zero.
* @param session The session to unreference
*/
void ai_session_unref(AISession* session);
/**
* Add a message to the session history.
* @param session The session
* @param role The message role ("user" or "assistant")
* @param content The message content
*/
void ai_session_add_message(AISession* session, const gchar* role, const gchar* content);
/**
* Clear the conversation history.
* @param session The session
*/
void ai_session_clear_history(AISession* session);
/**
* Get the current model for a session.
* @param session The session
* @return The model name (caller must not free)
*/
const gchar* ai_session_get_model(AISession* session);
/**
* Set the model for a session.
* @param session The session
* @param model The model name
*/
void ai_session_set_model(AISession* session, const gchar* model);
/* ========================================================================
* Request Handling
* ======================================================================== */
/**
* Send a prompt to the AI provider asynchronously.
* @param session The AI session containing provider and model
* @param prompt The prompt to send
* @param user_data User data (ProfAiWin* for UI display)
* @return TRUE if the request was successfully queued, FALSE otherwise
*/
gboolean ai_send_prompt(AISession* session, const gchar* prompt,
gpointer user_data);
/**
* Escape a string for JSON embedding.
* @param str The string to escape
* @return Newly allocated escaped string (caller must free)
*/
gchar* ai_json_escape(const gchar* str);
#endif /* AI_CLIENT_H */

View File

@@ -66,6 +66,8 @@
#include "omemo/omemo.h"
#endif
#include "ai/ai_client.h"
static char* _sub_autocomplete(ProfWin* window, const char* const input, gboolean previous);
static char* _notify_autocomplete(ProfWin* window, const char* const input, gboolean previous);
static char* _theme_autocomplete(ProfWin* window, const char* const input, gboolean previous);
@@ -137,6 +139,7 @@ static char* _strophe_autocomplete(ProfWin* window, const char* const input, gbo
static char* _adhoc_cmd_autocomplete(ProfWin* window, const char* const input, gboolean previous);
static char* _vcard_autocomplete(ProfWin* window, const char* const input, gboolean previous);
static char* _force_encryption_autocomplete(ProfWin* window, const char* const input, gboolean previous);
static char* _ai_autocomplete(ProfWin* window, const char* const input, gboolean previous);
static char* _script_autocomplete_func(const char* const prefix, gboolean previous, void* context);
@@ -278,6 +281,9 @@ static Autocomplete privacy_log_ac;
static Autocomplete color_ac;
static Autocomplete correction_ac;
static Autocomplete avatar_ac;
static Autocomplete ai_subcommands_ac;
static Autocomplete ai_set_subcommands_ac;
static Autocomplete ai_remove_subcommands_ac;
static Autocomplete url_ac;
static Autocomplete executable_ac;
static Autocomplete executable_param_ac;
@@ -452,7 +458,10 @@ static Autocomplete* all_acs[] = {
&vcard_togglable_param_ac,
&vcard_address_type_ac,
&force_encryption_ac,
&force_encryption_policy_ac
&force_encryption_policy_ac,
&ai_subcommands_ac,
&ai_set_subcommands_ac,
&ai_remove_subcommands_ac
};
static GHashTable* ac_funcs = NULL;
@@ -1153,6 +1162,19 @@ cmd_ac_init(void)
autocomplete_add(correction_ac, "off");
autocomplete_add(correction_ac, "char");
autocomplete_add(ai_subcommands_ac, "set");
autocomplete_add(ai_subcommands_ac, "remove");
autocomplete_add(ai_subcommands_ac, "start");
autocomplete_add(ai_subcommands_ac, "clear");
autocomplete_add(ai_subcommands_ac, "correct");
autocomplete_add(ai_subcommands_ac, "providers");
autocomplete_add(ai_set_subcommands_ac, "provider");
autocomplete_add(ai_set_subcommands_ac, "token");
autocomplete_add(ai_set_subcommands_ac, "org");
autocomplete_add(ai_remove_subcommands_ac, "provider");
autocomplete_add(avatar_ac, "set");
autocomplete_add(avatar_ac, "disable");
autocomplete_add(avatar_ac, "get");
@@ -1428,6 +1450,7 @@ cmd_ac_init(void)
g_hash_table_insert(ac_funcs, "/wins", _wins_autocomplete);
g_hash_table_insert(ac_funcs, "/wintitle", _wintitle_autocomplete);
g_hash_table_insert(ac_funcs, "/force-encryption", _force_encryption_autocomplete);
g_hash_table_insert(ac_funcs, "/ai", _ai_autocomplete);
}
void
@@ -4415,5 +4438,68 @@ _force_encryption_autocomplete(ProfWin* window, const char* const input, gboolea
}
result = autocomplete_param_with_ac(input, "/force-encryption", force_encryption_ac, TRUE, previous);
return result;
}
static char*
_ai_autocomplete(ProfWin* window, const char* const input, gboolean previous)
{
char* result = NULL;
/* Top-level /ai <subcommand> autocomplete (e.g., /ai s<tab> -> /ai set) */
result = autocomplete_param_with_func(input, "/ai set provider", ai_providers_find, previous, NULL);
if (result) {
return result;
}
// /ai set token <provider> <token> - autocomplete provider names
result = autocomplete_param_with_func(input, "/ai set token", ai_providers_find, previous, NULL);
if (result) {
return result;
}
// /ai set org <provider> <org_id> - autocomplete provider names
result = autocomplete_param_with_func(input, "/ai set org", ai_providers_find, previous, NULL);
if (result) {
return result;
}
// /ai set <subcommand> - autocomplete subcommands
result = autocomplete_param_with_ac(input, "/ai set", ai_set_subcommands_ac, TRUE, previous);
if (result) {
return result;
}
// /ai remove provider <name> - autocomplete provider names
result = autocomplete_param_with_func(input, "/ai remove provider", ai_providers_find, previous, NULL);
if (result) {
return result;
}
result = autocomplete_param_with_ac(input, "/ai remove", ai_remove_subcommands_ac, TRUE, previous);
if (result) {
return result;
}
// /ai start [<provider>/<model>] - autocomplete provider names
result = autocomplete_param_with_func(input, "/ai start", ai_providers_find, previous, NULL);
if (result) {
return result;
}
// /ai clear [<provider>] - autocomplete provider names
result = autocomplete_param_with_func(input, "/ai clear", ai_providers_find, previous, NULL);
if (result) {
return result;
}
// /ai correct <provider> <text>
result = autocomplete_param_with_func(input, "/ai correct", ai_providers_find, previous, NULL);
if (result) {
return result;
}
result = autocomplete_param_with_ac(input, "/ai", ai_subcommands_ac, FALSE, previous);
return result;
}

View File

@@ -2771,6 +2771,61 @@ static const struct cmd_t command_defs[] = {
"/force-encryption policy block")
},
{ CMD_PREAMBLE("/ai",
parse_args, 0, 5, NULL)
CMD_SUBFUNCS(
{ "set", cmd_ai_set },
{ "remove", cmd_ai_remove },
{ "start", cmd_ai_start },
{ "clear", cmd_ai_clear },
{ "correct", cmd_ai_correct },
{ "providers", cmd_ai_providers })
CMD_MAINFUNC(cmd_ai)
CMD_TAGS(
CMD_TAG_CHAT)
CMD_SYN(
"/ai",
"/ai set provider <name> <url>",
"/ai set token <provider> <token>",
"/ai set org <provider> <org_id>",
"/ai remove provider <name>",
"/ai providers",
"/ai providers-list",
"/ai start [<provider>/<model>]",
"/ai model <model>",
"/ai clear",
"/ai correct <message>")
CMD_DESC(
"Interact with AI models via OpenAI-compatible APIs. "
"Supports multiple providers (openai, perplexity, custom). "
"Each provider has its own API key and endpoint configuration. "
"Chat history is maintained per session and not persisted locally.")
CMD_ARGS(
{ "", "Display current AI settings and configured providers" },
{ "set provider <name> <url>", "Add or update a provider with custom API endpoint" },
{ "set token <provider> <token>", "Set API token for a provider (e.g., openai, perplexity)" },
{ "set org <provider> <org_id>", "Set organization ID for a provider (optional)" },
{ "remove provider <name>", "Remove a custom provider" },
{ "providers", "List all available providers" },
{ "providers-list", "List configured providers with keys status" },
{ "start [<provider>/<model>]", "Start new AI chat (e.g., openai/gpt-4o)" },
{ "model <model>", "Change model in current chat window" },
{ "clear", "Clear current chat history" },
{ "correct <message>", "Correct last user message and get new response" })
CMD_EXAMPLES(
"/ai",
"/ai set token openai sk-xxx",
"/ai set token perplexity pplx-xxx",
"/ai set provider custom https://my-api.com/v1/chat/completions",
"/ai set org openai my-org-id",
"/ai remove provider custom",
"/ai start openai/gpt-4o",
"/ai start perplexity/sonar",
"/ai providers-list",
"/ai clear",
"/ai correct I meant something else")
},
// NEXT-COMMAND (search helper)
};

View File

@@ -81,7 +81,6 @@
#include "tools/bookmark_ignore.h"
#include "tools/editor.h"
#include "plugins/plugins.h"
#include "ui/inputwin.h"
#include "ui/ui.h"
#include "ui/window_list.h"
#include "xmpp/avatar.h"
@@ -117,6 +116,8 @@
#include "tools/clipboard.h"
#endif
#include "ai/ai_client.h"
#ifdef HAVE_PYTHON
#include "plugins/python_plugins.h"
#endif
@@ -8326,7 +8327,7 @@ _cmd_execute_default(ProfWin* window, const char* inp)
}
// handle non commands in non chat or plugin windows
if (window->type != WIN_CHAT && window->type != WIN_MUC && window->type != WIN_PRIVATE && window->type != WIN_PLUGIN && window->type != WIN_XML) {
if (window->type != WIN_CHAT && window->type != WIN_MUC && window->type != WIN_PRIVATE && window->type != WIN_PLUGIN && window->type != WIN_XML && window->type != WIN_AI) {
cons_show("Unknown command: %s", inp);
cons_alert(NULL);
return TRUE;
@@ -8372,6 +8373,12 @@ _cmd_execute_default(ProfWin* window, const char* inp)
connection_send_stanza(inp);
break;
}
case WIN_AI:
{
ProfAiWin* aiwin = (ProfAiWin*)window;
cl_ev_send_ai_msg(aiwin, inp, NULL);
break;
}
default:
break;
}
@@ -10640,6 +10647,298 @@ cmd_vcard_save(ProfWin* window, const char* const command, gchar** args)
return TRUE;
}
gboolean
cmd_ai(ProfWin* window, const char* const command, gchar** args)
{
if (args[0] == NULL) {
// Display current AI settings
cons_show("AI Chat - OpenAI-compatible API client");
cons_show("");
// List available providers
GList* providers = ai_list_providers();
cons_show("Available providers:");
for (GList* curr = providers; curr; curr = g_list_next(curr)) {
AIProvider* provider = curr->data;
auto_gchar gchar* key = ai_get_provider_key(provider->name);
cons_show(" %s (URL: %s, Key: %s)",
provider->name,
provider->api_url,
key ? "set" : "not set");
}
g_list_free(providers);
cons_show("");
cons_show("Use '/ai start <provider>/<model>' to begin a chat.");
cons_show("Available models: https://models.litellm.ai/");
return TRUE;
}
cons_bad_cmd_usage(command);
return TRUE;
}
gboolean
cmd_ai_set(ProfWin* window, const char* const command, gchar** args)
{
if (args[1] == NULL) {
cons_bad_cmd_usage(command);
return TRUE;
}
if (g_strcmp0(args[1], "provider") == 0) {
// /ai set provider <name> <url>
if (g_strv_length(args) < 4) {
cons_bad_cmd_usage(command);
return TRUE;
}
if (ai_add_provider(args[2], args[3], NULL)) {
cons_show("Provider '%s' configured with URL: %s", args[2], args[3]);
} else {
cons_show_error("Failed to configure provider '%s'.", args[2]);
}
cons_show("");
return TRUE;
} else if (g_strcmp0(args[1], "token") == 0) {
// /ai set token <provider> <token>
if (g_strv_length(args) < 4) {
cons_bad_cmd_usage(command);
return TRUE;
}
ai_set_provider_key(args[2], args[3]);
cons_show("API token set for provider: %s", args[2]);
cons_show("");
return TRUE;
} else if (g_strcmp0(args[1], "org") == 0) {
// /ai set org <provider> <org_id>
if (g_strv_length(args) < 4) {
cons_bad_cmd_usage(command);
return TRUE;
}
AIProvider* provider = ai_get_provider(args[2]);
if (provider) {
g_free(provider->org_id);
provider->org_id = g_strdup(args[3]);
cons_show("Organization ID set for provider: %s", args[2]);
} else {
cons_show("Provider '%s' not found. Add it first with '/ai set provider'.", args[2]);
}
cons_show("");
return TRUE;
}
cons_bad_cmd_usage(command);
return TRUE;
}
gboolean
cmd_ai_remove(ProfWin* window, const char* const command, gchar** args)
{
// /ai remove provider <name>
if (g_strcmp0(args[1], "provider") != 0) {
cons_bad_cmd_usage(command);
return TRUE;
}
if (g_strv_length(args) < 3) {
cons_bad_cmd_usage(command);
return TRUE;
}
if (ai_remove_provider(args[2])) {
cons_show("Provider '%s' removed.", args[2]);
} else {
cons_show("Provider '%s' not found.", args[2]);
}
cons_show("");
return TRUE;
}
gboolean
cmd_ai_start(ProfWin* window, const char* const command, gchar** args)
{
// /ai start [<provider>/<model>]
const gchar* provider_model = (g_strv_length(args) >= 2) ? args[1] : NULL;
auto_gchar gchar* owned_provider_name = NULL;
const gchar* provider_name = "openai";
const gchar* model = "gpt-4o";
if (provider_model) {
const gchar* slash = strchr(provider_model, '/');
if (slash) {
owned_provider_name = g_strndup(provider_model, slash - provider_model);
provider_name = owned_provider_name;
model = slash + 1;
} else {
// Just a model name, use default provider
model = provider_model;
}
}
// Check if provider exists
AIProvider* provider = ai_get_provider(provider_name);
if (!provider) {
cons_show_error("Provider '%s' not found. Use '/ai set provider %s <url>' to add it.",
provider_name, provider_name);
return TRUE;
}
// Check for API key
gchar* api_key = ai_get_provider_key(provider_name);
if (!api_key || strlen(api_key) == 0) {
cons_show_error("No API key set for provider '%s'. Use '/ai set token %s <key>' first.",
provider_name, provider_name);
g_free(api_key);
return TRUE;
}
g_free(api_key);
// Create new AI session
AISession* session = ai_session_create(provider_name, model);
if (!session) {
log_error("[AI-CMD] Failed to create AI session");
cons_show_error("Failed to create AI session for %s/%s.", provider_name, model);
return TRUE;
}
log_debug("[AI-CMD] AI session created successfully");
// Create AI chat window
log_debug("[AI-CMD] Calling wins_new_ai()...");
ProfWin* ai_win = wins_new_ai(session);
if (!ai_win) {
log_error("[AI-CMD] wins_new_ai() returned NULL");
cons_show_error("Failed to create AI chat window.");
ai_session_unref(session);
return TRUE;
}
log_debug("[AI-CMD] wins_new_ai() returned successfully, window type: %d", ai_win->type);
// Add welcome message to the AI window
log_debug("[AI-CMD] Adding welcome messages...");
win_println(ai_win, THEME_DEFAULT, "-", "AI Chat: %s/%s", provider_name, model);
win_println(ai_win, THEME_DEFAULT, "-", "Type your message and press Enter to start a conversation.");
log_debug("[AI-CMD] Welcome messages added");
// Focus the new window
log_debug("[AI-CMD] Calling ui_focus_win()...");
ui_focus_win(ai_win);
log_debug("[AI-CMD] ui_focus_win() returned");
cons_show("Started AI chat: %s/%s", provider_name, model);
cons_show("");
log_debug("[AI-CMD] AI start command completed");
return TRUE;
}
gboolean
cmd_ai_clear(ProfWin* window, const char* const command, gchar** args)
{
// /ai clear
ProfAiWin* aiwin = (window && window->type == WIN_AI) ? (ProfAiWin*)window : wins_get_ai();
if (aiwin) {
assert(aiwin->memcheck == PROFAIWIN_MEMCHECK);
if (aiwin->session) {
ai_session_clear_history(aiwin->session);
}
cons_show("Chat history cleared.");
} else {
cons_show("No active AI chat window to clear.");
}
cons_show("");
return TRUE;
}
gboolean
cmd_ai_correct(ProfWin* window, const char* const command, gchar** args)
{
// /ai correct <message>
// Join all arguments from args[1] onwards to support multi-word prompts
auto_gchar gchar* prompt = g_strjoinv(" ", &args[1]);
if (prompt == NULL || strlen(prompt) == 0) {
cons_bad_cmd_usage(command);
return TRUE;
}
// Get current AI window
ProfAiWin* aiwin = wins_get_ai();
if (!aiwin) {
cons_show("No active AI chat window. Use '/ai start <provider>/<model>' first.");
return TRUE;
}
assert(aiwin->memcheck == PROFAIWIN_MEMCHECK);
if (!aiwin->session) {
cons_show("No active session in this chat window.");
return TRUE;
}
// Get the last user message and replace it
GList* history = aiwin->session->history;
GList* last_user_msg = NULL;
for (GList* curr = history; curr; curr = g_list_next(curr)) {
AIMessage* msg = curr->data;
if (g_strcmp0(msg->role, "user") == 0) {
last_user_msg = curr;
}
}
if (!last_user_msg) {
cons_show("No user messages in this chat to correct.");
return TRUE;
}
// Replace the last user message
AIMessage* msg = last_user_msg->data;
g_free(msg->content);
msg->content = g_strdup(prompt);
// Resend the prompt
cons_show("Correcting message...");
ai_send_prompt(aiwin->session, prompt, aiwin);
return TRUE;
}
gboolean
cmd_ai_providers(ProfWin* window, const char* const command, gchar** args)
{
if (args[1] == NULL || g_strcmp0(args[1], "list") != 0) {
// List all available providers
cons_show("Available AI providers:");
cons_show("");
cons_show(" openai - OpenAI API (https://api.openai.com)");
cons_show(" perplexity - Perplexity API (https://api.perplexity.ai)");
cons_show("");
cons_show("Add custom providers with: /ai set provider <name> <url>");
return TRUE;
}
// List configured providers with key status
cons_show("Configured providers:");
cons_show("");
GList* providers = ai_list_providers();
for (GList* curr = providers; curr; curr = g_list_next(curr)) {
AIProvider* provider = curr->data;
gchar* key = ai_get_provider_key(provider->name);
cons_show(" %s", provider->name);
cons_show(" URL: %s", provider->api_url);
cons_show(" Key: %s", key ? "configured" : "NOT configured");
if (provider->org_id && strlen(provider->org_id) > 0) {
cons_show(" Org: %s", provider->org_id);
}
cons_show("");
g_free(key);
}
g_list_free(providers);
return TRUE;
}
gboolean
cmd_force_encryption(ProfWin* window, const char* const command, gchar** args)
{

View File

@@ -166,6 +166,13 @@ gboolean cmd_console(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_command_list(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_command_exec(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_change_password(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_ai(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_ai_set(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_ai_remove(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_ai_start(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_ai_clear(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_ai_correct(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_ai_providers(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_plugins(ProfWin* window, const char* const command, gchar** args);
gboolean cmd_plugins_sourcepath(ProfWin* window, const char* const command, gchar** args);

View File

@@ -66,6 +66,7 @@
#define PREF_GROUP_MUC "muc"
#define PREF_GROUP_PLUGINS "plugins"
#define PREF_GROUP_EXECUTABLES "executables"
#define PREF_GROUP_AI "ai"
#define INPBLOCK_DEFAULT 1000
@@ -1706,6 +1707,85 @@ _save_prefs(void)
save_keyfile(&prefs_prof_keyfile);
}
/* ========================================================================
* AI Token Management
* ======================================================================== */
gboolean
prefs_ai_set_token(const char* const provider, const char* const token)
{
if (!provider)
return FALSE;
if (!prefs)
return FALSE;
if (token) {
g_key_file_set_string(prefs, PREF_GROUP_AI, provider, token);
_save_prefs();
return TRUE;
} else {
return prefs_ai_remove_token(provider);
}
}
gboolean
prefs_ai_remove_token(const char* const provider)
{
if (!provider)
return FALSE;
if (!prefs)
return FALSE;
if (!g_key_file_has_key(prefs, PREF_GROUP_AI, provider, NULL)) {
return FALSE;
}
g_key_file_remove_key(prefs, PREF_GROUP_AI, provider, NULL);
_save_prefs();
return TRUE;
}
char*
prefs_ai_get_token(const char* const provider)
{
if (!provider || !prefs)
return NULL;
return g_key_file_get_string(prefs, PREF_GROUP_AI, provider, NULL);
}
GList*
prefs_ai_list_tokens(void)
{
if (!prefs || !g_key_file_has_group(prefs, PREF_GROUP_AI)) {
return NULL;
}
GList* result = NULL;
gsize len;
auto_gcharv gchar** keys = g_key_file_get_keys(prefs, PREF_GROUP_AI, &len, NULL);
for (gsize i = 0; i < len; i++) {
char* name = keys[i];
auto_gchar gchar* value = g_key_file_get_string(prefs, PREF_GROUP_AI, name, NULL);
if (value) {
result = g_list_append(result, g_strdup(name));
}
}
return result;
}
void
prefs_free_ai_tokens(GList* tokens)
{
if (tokens) {
g_list_free_full(tokens, g_free);
}
}
// get the preference group for a specific preference
// for example the PREF_BEEP setting ("beep" in .profrc, see _get_key) belongs
// to the [ui] section.
@@ -1865,6 +1945,9 @@ _get_group(preference_t pref)
return PREF_GROUP_OMEMO;
case PREF_OX_LOG:
return PREF_GROUP_OX;
case PREF_AI_PROVIDER:
case PREF_AI_API_KEY:
return PREF_GROUP_AI;
default:
return NULL;
}
@@ -2142,6 +2225,10 @@ _get_key(preference_t pref)
return "stamp.incoming";
case PREF_OX_LOG:
return "log";
case PREF_AI_PROVIDER:
return "provider";
case PREF_AI_API_KEY:
return "api_key";
case PREF_MOOD:
return "mood";
case PREF_VCARD_PHOTO_CMD:
@@ -2319,6 +2406,10 @@ _get_default_string(preference_t pref)
return "on";
case PREF_FORCE_ENCRYPTION_MODE:
return "resend-to-confirm";
case PREF_AI_PROVIDER:
return "openai";
case PREF_AI_API_KEY:
return "";
default:
return NULL;
}

View File

@@ -183,6 +183,9 @@ typedef enum {
PREF_OX_LOG,
PREF_MOOD,
PREF_STROPHE_VERBOSITY,
PREF_AI_PROVIDER,
PREF_AI_API_KEY,
PREF_AI_DEFAULT_MODEL,
PREF_STROPHE_SM_ENABLED,
PREF_STROPHE_SM_RESEND,
PREF_VCARD_PHOTO_CMD,
@@ -356,4 +359,11 @@ gboolean prefs_get_room_notify(const char* const roomjid);
gboolean prefs_get_room_notify_mention(const char* const roomjid);
gboolean prefs_get_room_notify_trigger(const char* const roomjid);
/* AI token management */
gboolean prefs_ai_set_token(const char* const provider, const char* const token);
gboolean prefs_ai_remove_token(const char* const provider);
char* prefs_ai_get_token(const char* const provider);
GList* prefs_ai_list_tokens(void);
void prefs_free_ai_tokens(GList* tokens);
#endif

View File

@@ -37,8 +37,10 @@
#include "config.h"
#include <stdlib.h>
#include <assert.h>
#include <glib.h>
#include "ai/ai_client.h"
#include "log.h"
#include "chatlog.h"
#include "database.h"
@@ -47,7 +49,7 @@
#include "event/common.h"
#include "plugins/plugins.h"
#include "ui/inputwin.h"
#include "ui/window_list.h"
#include "ui/window.h"
#include "xmpp/chat_session.h"
#include "xmpp/session.h"
#include "xmpp/xmpp.h"
@@ -284,3 +286,24 @@ allow_unencrypted_message(ProfChatWin* chatwin, const char* const msg)
win_println((ProfWin*)chatwin, THEME_ERROR, "-", "Message not sent: invalid encryption mode (%s). Use '/force-encryption policy resend-to-confirm'.", force_enc_mode);
return FALSE;
}
void
cl_ev_send_ai_msg(ProfAiWin* aiwin, const char* const message, const char* const id)
{
if (!aiwin || !message) {
return;
}
assert(aiwin->memcheck == PROFAIWIN_MEMCHECK);
if (!aiwin->session) {
log_error("[AI] AI session not initialized");
return;
}
// Display user message in AI window.
win_print_outgoing(&aiwin->window, ">>", id, NULL, message);
// Send to AI provider.
ai_send_prompt(aiwin->session, message, aiwin);
}

View File

@@ -51,6 +51,7 @@ void cl_ev_send_msg(ProfChatWin* chatwin, const char* const msg, const char* con
void cl_ev_send_muc_msg_corrected(ProfMucWin* mucwin, const char* const msg, const char* const oob_url, gboolean correct_last_msg);
void cl_ev_send_muc_msg(ProfMucWin* mucwin, const char* const msg, const char* const oob_url);
void cl_ev_send_priv_msg(ProfPrivateWin* privwin, const char* const msg, const char* const oob_url);
void cl_ev_send_ai_msg(ProfAiWin* aiwin, const char* const message, const char* const id);
// Checks if an unencrypted message can be sent based on encryption preferences.
// Returns TRUE if allowed, FALSE if blocked.

View File

@@ -69,6 +69,7 @@
#include "xmpp/xmpp.h"
#include "xmpp/muc.h"
#include "xmpp/chat_session.h"
#include "ai/ai_client.h"
#include "xmpp/chat_state.h"
#include "xmpp/contact.h"
#include "xmpp/roster_list.h"
@@ -249,6 +250,7 @@ _init(char* log_level, char* config_file, char* log_file, char* theme_name)
}
session_init();
cmd_init();
ai_client_init();
log_info("Initialising contact list");
muc_init();
tlscerts_init();

61
src/ui/aiwin.c Normal file
View File

@@ -0,0 +1,61 @@
/*
* aiwin.c - AI Chat Window Management
*
* Provides functions for managing the AI chat window (ProfAiWin) in the
* profanity client. This includes retrieving window strings for identification,
* displaying AI/LLM responses in the chat view, and handling error messages
* from AI interactions.
*
* Key functions:
* aiwin_get_string() - Returns a descriptive string for the window
* aiwin_display_response() - Displays an AI/LLM response and appends it
* to the conversation history
* aiwin_display_error() - Displays an error message from AI operations
*
* vim: expandtab:ts=4:sts=4:sw=4
*/
#include "config.h"
#include <assert.h>
#include "ai/ai_client.h"
#include "log.h"
#include "ui/ui.h"
#include "ui/win_types.h"
char*
aiwin_get_string(ProfAiWin* win)
{
assert(win->memcheck == PROFAIWIN_MEMCHECK);
return g_strdup_printf("AI Chat (%s: %s)", win->session->provider_name, win->session->model);
}
void
aiwin_display_response(ProfAiWin* win, const char* response)
{
log_debug("[AI-WIN] aiwin_display_response ENTER: win=%p, response='%s'", (void*)win, response);
assert(win->memcheck == PROFAIWIN_MEMCHECK);
if (!response) {
log_error("[AI-WIN] FAIL: null response");
return;
}
// Display AI response
win_println(&win->window, THEME_DEFAULT, "<< LLM:", "%s", response);
log_debug("[AI-WIN] Displayed AI response");
}
void
aiwin_display_error(ProfAiWin* win, const char* error_msg)
{
log_debug("[AI-WIN] aiwin_display_error ENTER: win=%p, error='%s'", (void*)win, error_msg);
assert(win->memcheck == PROFAIWIN_MEMCHECK);
const char* msg = error_msg ? error_msg : "Unknown error";
win_println(&win->window, THEME_ERROR, "[ERROR]", "%s", msg);
// Also show error in console so user sees it regardless of active window
cons_show_error("AI Error: %s", msg);
}

View File

@@ -386,6 +386,8 @@ ProfWin* win_create_config(const char* const title, DataForm* form, ProfConfWinC
ProfWin* win_create_private(const char* const fulljid);
ProfWin* win_create_plugin(const char* const plugin_name, const char* const tag);
ProfWin* win_create_vcard(vCard* vcard);
ProfWin* win_create_ai(AISession* session);
ProfWin* wins_new_ai(AISession* session);
void win_update_virtual(ProfWin* window);
void win_free(ProfWin* window);
gboolean win_notify_remind(ProfWin* window);
@@ -445,4 +447,9 @@ void notify_invite(const char* const from, const char* const room, const char* c
void notify(const char* const message, int timeout, const char* const category);
void notify_subscription(const char* const from);
/* AI window */
char* aiwin_get_string(ProfAiWin* win);
void aiwin_display_response(ProfAiWin* win, const char* response);
void aiwin_display_error(ProfAiWin* win, const char* error_msg);
#endif

View File

@@ -62,6 +62,7 @@
#define PROFXMLWIN_MEMCHECK 87333463
#define PROFPLUGINWIN_MEMCHECK 43434777
#define PROFVCARDWIN_MEMCHECK 68947523
#define PROFAIWIN_MEMCHECK 91827364
typedef enum {
FIELD_HIDDEN,
@@ -144,7 +145,8 @@ typedef enum {
WIN_PRIVATE,
WIN_XML,
WIN_PLUGIN,
WIN_VCARD
WIN_VCARD,
WIN_AI
} win_type_t;
typedef enum {
@@ -258,4 +260,16 @@ typedef struct prof_vcard_win_t
unsigned long memcheck;
} ProfVcardWin;
/* Forward declaration */
typedef struct ai_session_t AISession;
typedef struct prof_ai_win_t
{
ProfWin window;
ProfBuff message_buffer;
GString* conversation_history;
AISession* session;
unsigned long memcheck;
} ProfAiWin;
#endif

View File

@@ -36,6 +36,7 @@
#include "config.h"
#include "database.h"
#include "ui/win_types.h"
#include "ui/window_list.h"
#include <stdlib.h>
@@ -62,6 +63,7 @@
#include "ui/screen.h"
#include "xmpp/xmpp.h"
#include "xmpp/roster_list.h"
#include "ai/ai_client.h"
static const char* LOADING_MESSAGE = "Loading older messages…";
static const char* CONS_WIN_TITLE = "CProof. Type /help for help information.";
@@ -329,6 +331,22 @@ win_create_vcard(vCard* vcard)
return &new_win->window;
}
ProfWin*
win_create_ai(AISession* session)
{
ProfAiWin* new_win = g_new0(ProfAiWin, 1);
new_win->window.type = WIN_AI;
new_win->window.scroll_state = WIN_SCROLL_INNER;
new_win->window.layout = _win_create_simple_layout();
new_win->message_buffer = buffer_create();
new_win->conversation_history = g_string_new("");
new_win->session = session ? ai_session_ref(session) : NULL;
new_win->memcheck = PROFAIWIN_MEMCHECK;
return &new_win->window;
}
gchar*
win_get_title(ProfWin* window)
{
@@ -407,6 +425,13 @@ win_get_title(ProfWin* window)
return g_string_free(title, FALSE);
}
case WIN_AI:
{
const ProfAiWin* aiwin = (ProfAiWin*)window;
assert(aiwin->memcheck == PROFAIWIN_MEMCHECK);
return g_strdup_printf("AI Assistant (%s: %s)", aiwin->session->provider_name, aiwin->session->model);
}
}
assert(FALSE);
}
@@ -454,6 +479,10 @@ win_get_tab_identifier(ProfWin* window)
{
return strdup("vcard");
}
case WIN_AI:
{
return strdup("ai");
}
}
assert(FALSE);
}
@@ -536,6 +565,12 @@ win_to_string(ProfWin* window)
ProfVcardWin* vcardwin = (ProfVcardWin*)window;
return vcardwin_get_string(vcardwin);
}
case WIN_AI:
{
ProfAiWin* aiwin = (ProfAiWin*)window;
assert(aiwin->memcheck == PROFAIWIN_MEMCHECK);
return aiwin_get_string(aiwin);
}
}
assert(FALSE);
}
@@ -662,6 +697,17 @@ win_free(ProfWin* window)
free(pluginwin->plugin_name);
break;
}
case WIN_AI:
{
ProfAiWin* aiwin = (ProfAiWin*)window;
assert(aiwin->memcheck == PROFAIWIN_MEMCHECK);
buffer_free(aiwin->message_buffer);
g_string_free(aiwin->conversation_history, TRUE);
if (aiwin->session) {
ai_session_unref(aiwin->session);
}
break;
}
default:
break;
}

View File

@@ -44,9 +44,11 @@
#include "common.h"
#include "config/preferences.h"
#include "log.h"
#include "config/theme.h"
#include "plugins/plugins.h"
#include "ui/ui.h"
#include "ui/window.h"
#include "ui/window_list.h"
#include "xmpp/xmpp.h"
#include "xmpp/roster_list.h"
@@ -374,6 +376,8 @@ wins_set_current_by_num(int i)
status_bar_active(1, conswin->type, "console");
}
}
} else {
log_error("Window not found for index %d", i);
}
}
@@ -714,6 +718,20 @@ wins_new_vcard(vCard* vcard)
return newwin;
}
ProfWin*
wins_new_ai(AISession* session)
{
int result = _wins_get_next_available_num(keys);
ProfWin* newwin = win_create_ai(session);
if (!newwin) {
return NULL;
}
_wins_htable_insert(windows, GINT_TO_POINTER(result), newwin);
autocomplete_add(wins_ac, "ai");
autocomplete_add(wins_close_ac, "ai");
return newwin;
}
gboolean
wins_do_notify_remind(void)
{
@@ -841,7 +859,7 @@ wins_get_prune_wins(void)
while (curr) {
ProfWin* window = curr->data;
if (win_unread(window) == 0 && window->type != WIN_MUC && window->type != WIN_CONFIG && window->type != WIN_XML && window->type != WIN_CONSOLE) {
if (win_unread(window) == 0 && window->type != WIN_MUC && window->type != WIN_CONFIG && window->type != WIN_XML && window->type != WIN_CONSOLE && window->type != WIN_AI) {
result = g_slist_append(result, window);
}
curr = g_list_next(curr);
@@ -849,6 +867,45 @@ wins_get_prune_wins(void)
return result;
}
ProfAiWin*
wins_get_ai(void)
{
GList* curr = values;
while (curr) {
ProfWin* window = curr->data;
if (window->type == WIN_AI) {
ProfAiWin* aiwin = (ProfAiWin*)window;
assert(aiwin->memcheck == PROFAIWIN_MEMCHECK);
return aiwin;
}
curr = g_list_next(curr);
}
return NULL;
}
gboolean
wins_ai_exists(ProfAiWin* const aiwin)
{
if (!aiwin) {
return FALSE;
}
GList* curr = values;
while (curr) {
ProfWin* window = curr->data;
if (window->type == WIN_AI) {
if ((ProfAiWin*)window == aiwin) {
return TRUE;
}
}
curr = g_list_next(curr);
}
return FALSE;
}
void
wins_lost_connection(void)
{

View File

@@ -63,6 +63,8 @@ ProfPrivateWin* wins_get_private(const char* const fulljid);
ProfPluginWin* wins_get_plugin(const char* const tag);
ProfXMLWin* wins_get_xmlconsole(void);
ProfVcardWin* wins_get_vcard(void);
ProfAiWin* wins_get_ai(void);
gboolean wins_ai_exists(ProfAiWin* const aiwin);
void wins_close_plugin(char* tag);

View File

@@ -0,0 +1,463 @@
#include "prof_cmocka.h"
#include "common.h"
#include "ai/ai_client.h"
#include <stdlib.h>
/* ========================================================================
* Setup/Teardown
* ======================================================================== */
int
ai_client_setup(void** state)
{
ai_client_init();
return 0;
}
int
ai_client_teardown(void** state)
{
ai_client_shutdown();
return 0;
}
/* ========================================================================
* Provider Management Tests
* ======================================================================== */
void
test_ai_client_init(void** state)
{
/* After init, default providers should exist */
AIProvider* openai = ai_get_provider("openai");
assert_non_null(openai);
assert_string_equal("openai", openai->name);
assert_string_equal("https://api.openai.com/", openai->api_url);
AIProvider* perplexity = ai_get_provider("perplexity");
assert_non_null(perplexity);
assert_string_equal("perplexity", perplexity->name);
assert_string_equal("https://api.perplexity.ai/", perplexity->api_url);
}
void
test_ai_add_provider(void** state)
{
/* Add a custom provider (hash table owns ref; caller gets non-owning pointer) */
AIProvider* provider = ai_add_provider("custom", "https://custom.api.com/v1", "my-org");
assert_non_null(provider);
assert_string_equal("custom", provider->name);
assert_string_equal("https://custom.api.com/v1", provider->api_url);
assert_string_equal("my-org", provider->org_id);
/* Update existing provider (returns ref; caller owns it) */
AIProvider* updated = ai_add_provider("custom", "https://new.api.com/v1", NULL);
assert_non_null(updated);
assert_string_equal("https://new.api.com/v1", updated->api_url);
assert_null(updated->org_id);
ai_provider_unref(updated);
}
void
test_ai_remove_provider(void** state)
{
/* Remove default provider should fail */
assert_false(ai_remove_provider("nonexistent"));
/* Add and remove custom provider */
ai_add_provider("temp", "https://temp.api.com/v1", NULL);
assert_true(ai_remove_provider("temp"));
assert_null(ai_get_provider("temp"));
}
void
test_ai_list_providers(void** state)
{
GList* providers = ai_list_providers();
assert_non_null(providers);
assert_int_equal(2, g_list_length(providers)); /* openai and perplexity */
/* Free list (ai_list_providers returns non-ref'd providers; caller must not unref) */
g_list_free(providers);
/* Add another provider */
ai_add_provider("test", "https://test.api.com/v1", NULL);
providers = ai_list_providers();
assert_int_equal(3, g_list_length(providers));
/* Free list */
g_list_free(providers);
}
/* ========================================================================
* API Key Tests
* ======================================================================== */
void
test_ai_set_provider_key(void** state)
{
ai_set_provider_key("openai", "sk-test-key-123");
{
auto_gchar gchar* key = ai_get_provider_key("openai");
assert_non_null(key);
assert_string_equal("sk-test-key-123", key);
}
/* Update key */
ai_set_provider_key("openai", "sk-new-key-456");
{
auto_gchar gchar* key = ai_get_provider_key("openai");
assert_string_equal("sk-new-key-456", key);
}
/* Remove key */
ai_set_provider_key("openai", NULL);
{
auto_gchar gchar* key = ai_get_provider_key("openai");
assert_null(key);
}
}
void
test_ai_get_provider_key(void** state)
{
/* No key set initially */
{
auto_gchar gchar* key = ai_get_provider_key("openai");
assert_null(key);
}
/* Set and get key */
ai_set_provider_key("perplexity", "pplx-abc123");
{
auto_gchar gchar* key = ai_get_provider_key("perplexity");
assert_non_null(key);
assert_string_equal("pplx-abc123", key);
}
/* Wrong provider returns null */
{
auto_gchar gchar* key = ai_get_provider_key("openai");
assert_null(key);
}
}
/* ========================================================================
* Session Tests
* ======================================================================== */
void
test_ai_session_create(void** state)
{
AISession* session = ai_session_create("openai", "gpt-4");
assert_non_null(session);
assert_string_equal("openai", session->provider_name);
assert_string_equal("gpt-4", session->model);
assert_null(session->api_key); /* No key set */
ai_session_unref(session);
}
void
test_ai_session_ref_unref(void** state)
{
AISession* session = ai_session_create("openai", "gpt-4");
assert_non_null(session);
/* Reference */
AISession* ref = ai_session_ref(session);
assert_true(ref == session);
/* Unreference twice */
ai_session_unref(session);
ai_session_unref(ref); /* Should free here */
}
void
test_ai_session_add_message(void** state)
{
AISession* session = ai_session_create("openai", "gpt-4");
assert_non_null(session);
ai_session_add_message(session, "user", "Hello");
ai_session_add_message(session, "assistant", "Hi there!");
assert_int_equal(2, g_list_length(session->history));
AIMessage* first = session->history->data;
assert_string_equal("user", first->role);
assert_string_equal("Hello", first->content);
AIMessage* second = g_list_next(session->history)->data;
assert_string_equal("assistant", second->role);
assert_string_equal("Hi there!", second->content);
ai_session_unref(session);
}
void
test_ai_session_clear_history(void** state)
{
AISession* session = ai_session_create("openai", "gpt-4");
ai_session_add_message(session, "user", "Message 1");
ai_session_add_message(session, "user", "Message 2");
ai_session_add_message(session, "assistant", "Response");
assert_int_equal(3, g_list_length(session->history));
ai_session_clear_history(session);
assert_int_equal(0, g_list_length(session->history));
ai_session_unref(session);
}
void
test_ai_session_set_model(void** state)
{
AISession* session = ai_session_create("openai", "gpt-4");
assert_string_equal("gpt-4", session->model);
ai_session_set_model(session, "gpt-3.5-turbo");
assert_string_equal("gpt-3.5-turbo", session->model);
ai_session_unref(session);
}
/* ========================================================================
* JSON Escape Tests
* ======================================================================== */
void
test_ai_json_escape(void** state)
{
gchar* escaped = ai_json_escape("hello \"world\"");
assert_string_equal("hello \\\"world\\\"", escaped);
g_free(escaped);
}
void
test_ai_json_escape_null(void** state)
{
gchar* escaped = ai_json_escape(NULL);
assert_string_equal("", escaped);
g_free(escaped);
}
void
test_ai_json_escape_empty(void** state)
{
gchar* escaped = ai_json_escape("");
assert_string_equal("", escaped);
g_free(escaped);
}
void
test_ai_json_escape_special_chars(void** state)
{
gchar* escaped = ai_json_escape("line1\nline2\ttab\\backslash\"quote");
assert_string_equal("line1\\nline2\\ttab\\\\backslash\\\"quote", escaped);
g_free(escaped);
}
void
test_ai_json_escape_percent_signs(void** state)
{
/* Critical: % characters in content must be escaped for JSON, not treated as format specifiers */
gchar* escaped = ai_json_escape("100% complete with %s and %d format strings");
assert_string_equal("100% complete with %s and %d format strings", escaped);
g_free(escaped);
}
void
test_ai_json_escape_backslash_quote(void** state)
{
/* Test escaped quote handling */
gchar* escaped = ai_json_escape("He said \"hello\" and \\ goodbye");
assert_string_equal("He said \\\"hello\\\" and \\\\ goodbye", escaped);
g_free(escaped);
}
void
test_ai_session_api_key_is_copied(void** state)
{
/* Verify that session owns its own copy of the API key */
ai_set_provider_key("openai", "sk-test-key-123");
AISession* session = ai_session_create("openai", "gpt-4");
assert_non_null(session);
assert_string_equal("sk-test-key-123", session->api_key);
/* Remove the provider key - session should still have its copy */
ai_set_provider_key("openai", NULL);
assert_non_null(session->api_key);
assert_string_equal("sk-test-key-123", session->api_key);
ai_session_unref(session);
}
void
test_ai_add_provider_update_existing(void** state)
{
/* Add a provider (hash table owns ref) */
AIProvider* provider = ai_add_provider("custom", "https://first.api.com/v1", "org1");
assert_non_null(provider);
assert_string_equal("https://first.api.com/v1", provider->api_url);
assert_string_equal("org1", provider->org_id);
/* Update the same provider (returns ref) */
provider = ai_add_provider("custom", "https://second.api.com/v1", "org2");
assert_non_null(provider);
assert_string_equal("https://second.api.com/v1", provider->api_url);
assert_string_equal("org2", provider->org_id);
ai_provider_unref(provider);
}
void
test_ai_add_provider_null_name_returns_null(void** state)
{
assert_null(ai_add_provider(NULL, "https://api.com/v1", NULL));
}
void
test_ai_add_provider_null_url_returns_null(void** state)
{
assert_null(ai_add_provider("test", NULL, NULL));
}
void
test_ai_session_create_null_provider_returns_null(void** state)
{
assert_null(ai_session_create("nonexistent", "gpt-4"));
}
void
test_ai_session_create_null_model_returns_null(void** state)
{
assert_null(ai_session_create("openai", NULL));
}
void
test_ai_session_api_key_null_when_no_key_set(void** state)
{
/* openai has no key set by default */
AISession* session = ai_session_create("openai", "gpt-4");
assert_non_null(session);
assert_null(session->api_key);
ai_session_unref(session);
}
/* ========================================================================
* Provider Autocomplete Tests
* ======================================================================== */
void
test_ai_providers_find_forward(void** state)
{
/* Test forward iteration - should return first match */
auto_gchar gchar* result = ai_providers_find("o", FALSE, NULL);
assert_non_null(result);
assert_string_equal("openai", result);
}
void
test_ai_providers_find_forward_perplexity(void** state)
{
/* Test forward iteration for perplexity */
auto_gchar gchar* result = ai_providers_find("p", FALSE, NULL);
assert_non_null(result);
assert_string_equal("perplexity", result);
}
void
test_ai_providers_find_forward_custom(void** state)
{
/* Add a custom provider and test */
ai_add_provider("custom", "https://custom.api.com/v1", NULL);
auto_gchar gchar* result = ai_providers_find("c", FALSE, NULL);
assert_non_null(result);
assert_string_equal("custom", result);
}
void
test_ai_providers_find_forward_no_match(void** state)
{
/* Test no match */
auto_gchar gchar* result = ai_providers_find("z", FALSE, NULL);
assert_null(result);
}
void
test_ai_providers_find_forward_partial_match(void** state)
{
/* Test partial match - should return providers starting with "ope" */
auto_gchar gchar* result = ai_providers_find("ope", FALSE, NULL);
assert_non_null(result);
assert_string_equal("openai", result);
}
void
test_ai_providers_find_next(void** state)
{
/* Test that stateless implementation returns same result each call */
auto_gchar gchar* result1 = ai_providers_find("o", FALSE, NULL);
assert_non_null(result1);
assert_string_equal("openai", result1);
/* Second call with same params returns same result (stateless) */
auto_gchar gchar* result2 = ai_providers_find("o", FALSE, NULL);
assert_non_null(result2);
assert_string_equal("openai", result2);
}
void
test_ai_providers_find_previous(void** state)
{
/* Test that previous=TRUE returns last match in list */
/* With only "openai" starting with "o", both FALSE and TRUE return same result */
auto_gchar gchar* result1 = ai_providers_find("o", FALSE, NULL);
assert_non_null(result1);
assert_string_equal("openai", result1);
/* previous=TRUE also returns "openai" (only one match, so first==last) */
auto_gchar gchar* result2 = ai_providers_find("o", TRUE, NULL);
assert_non_null(result2);
assert_string_equal("openai", result2);
}
void
test_ai_providers_find_null_search_str(void** state)
{
/* NULL search_str triggers cycling: returns first provider in list */
auto_gchar gchar* result = ai_providers_find(NULL, FALSE, NULL);
assert_non_null(result);
assert_string_equal("openai", result);
}
void
test_ai_providers_find_empty_search_str(void** state)
{
/* Empty search_str triggers cycling: returns first provider in list */
auto_gchar gchar* result = ai_providers_find("", FALSE, NULL);
assert_non_null(result);
assert_string_equal("openai", result);
}
void
test_ai_providers_find_case_insensitive(void** state)
{
/* Test that matching is case-insensitive (via g_ascii_strdown) */
auto_gchar gchar* result = ai_providers_find("OPENAI", FALSE, NULL);
assert_non_null(result);
assert_string_equal("openai", result);
result = ai_providers_find("OpenAI", FALSE, NULL);
assert_non_null(result);
assert_string_equal("openai", result);
result = ai_providers_find("openai", FALSE, NULL);
assert_non_null(result);
assert_string_equal("openai", result);
}

View File

@@ -0,0 +1,42 @@
/*
* test_ai_client.h - AI client unit test declarations
*/
int ai_client_setup(void** state);
int ai_client_teardown(void** state);
void test_ai_client_init(void** state);
void test_ai_add_provider(void** state);
void test_ai_remove_provider(void** state);
void test_ai_list_providers(void** state);
void test_ai_set_provider_key(void** state);
void test_ai_get_provider_key(void** state);
void test_ai_session_create(void** state);
void test_ai_session_ref_unref(void** state);
void test_ai_session_add_message(void** state);
void test_ai_session_clear_history(void** state);
void test_ai_session_set_model(void** state);
void test_ai_json_escape(void** state);
void test_ai_json_escape_null(void** state);
void test_ai_json_escape_empty(void** state);
void test_ai_json_escape_special_chars(void** state);
void test_ai_json_escape_percent_signs(void** state);
void test_ai_json_escape_backslash_quote(void** state);
void test_ai_session_api_key_is_copied(void** state);
void test_ai_add_provider_update_existing(void** state);
void test_ai_add_provider_null_name_returns_null(void** state);
void test_ai_add_provider_null_url_returns_null(void** state);
void test_ai_session_create_null_provider_returns_null(void** state);
void test_ai_session_create_null_model_returns_null(void** state);
void test_ai_session_api_key_null_when_no_key_set(void** state);
/* Provider autocomplete tests */
void test_ai_providers_find_forward(void** state);
void test_ai_providers_find_forward_perplexity(void** state);
void test_ai_providers_find_forward_custom(void** state);
void test_ai_providers_find_forward_no_match(void** state);
void test_ai_providers_find_forward_partial_match(void** state);
void test_ai_providers_find_next(void** state);
void test_ai_providers_find_previous(void** state);
void test_ai_providers_find_null_search_str(void** state);
void test_ai_providers_find_empty_search_str(void** state);
void test_ai_providers_find_case_insensitive(void** state);

View File

@@ -0,0 +1,41 @@
/*
* stub_ai.c - Stubs for AI window functions
*/
#include "ui/window.h"
#include "ai/ai_client.h"
ProfWin*
win_create_ai(AISession* session)
{
/* Return NULL to simulate failure in unit tests */
(void)session;
return NULL;
}
void
aiwin_display_response(ProfAiWin* win, const char* response)
{
/* Stub: do nothing */
(void)win;
(void)response;
}
void
aiwin_display_error(ProfAiWin* win, const char* error_msg)
{
/* Stub: do nothing */
(void)win;
(void)error_msg;
}
void
win_print_outgoing(ProfWin* window, const char* show_char, const char* const id, const char* const replace_id, const char* const message)
{
/* Stub: do nothing */
(void)window;
(void)show_char;
(void)id;
(void)replace_id;
(void)message;
}

View File

@@ -36,6 +36,7 @@
#include "test_form.h"
#include "test_callbacks.h"
#include "test_plugins_disco.h"
#include "test_ai_client.h"
#define muc_unit_test(f) cmocka_unit_test_setup_teardown(f, muc_before_test, muc_after_test)
@@ -656,6 +657,43 @@ main(int argc, char* argv[])
cmocka_unit_test_setup_teardown(test_allow_unencrypted_message_confirms_on_second_attempt, load_preferences, close_preferences),
cmocka_unit_test_setup_teardown(test_cmd_force_encryption_invalid_policy, load_preferences, close_preferences),
cmocka_unit_test_setup_teardown(test_allow_unencrypted_message_invalid_mode, load_preferences, close_preferences),
// AI client tests
cmocka_unit_test_setup_teardown(test_ai_client_init, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_add_provider, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_remove_provider, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_list_providers, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_set_provider_key, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_get_provider_key, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_session_create, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_session_ref_unref, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_session_add_message, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_session_clear_history, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_session_set_model, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_session_api_key_is_copied, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_add_provider_update_existing, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_add_provider_null_name_returns_null, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_add_provider_null_url_returns_null, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_session_create_null_provider_returns_null, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_session_create_null_model_returns_null, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_session_api_key_null_when_no_key_set, ai_client_setup, ai_client_teardown),
/* Provider autocomplete tests */
cmocka_unit_test_setup_teardown(test_ai_providers_find_forward, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_providers_find_forward_perplexity, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_providers_find_forward_custom, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_providers_find_forward_no_match, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_providers_find_forward_partial_match, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_providers_find_next, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_providers_find_previous, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_providers_find_null_search_str, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_providers_find_empty_search_str, ai_client_setup, ai_client_teardown),
cmocka_unit_test_setup_teardown(test_ai_providers_find_case_insensitive, ai_client_setup, ai_client_teardown),
cmocka_unit_test(test_ai_json_escape),
cmocka_unit_test(test_ai_json_escape_null),
cmocka_unit_test(test_ai_json_escape_empty),
cmocka_unit_test(test_ai_json_escape_special_chars),
cmocka_unit_test(test_ai_json_escape_percent_signs),
cmocka_unit_test(test_ai_json_escape_backslash_quote),
};
return cmocka_run_group_tests(all_tests, NULL, NULL);
}