Compare commits

..

36 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
f84ed1bf6a perf(functests): speedup — profrc pre-baking, pty-close shutdown, parallel port pools
All checks were successful
CI Code / Check spelling (pull_request) Successful in 18s
CI Code / Check coding style (pull_request) Successful in 32s
CI Code / Code Coverage (pull_request) Successful in 2m46s
CI Code / Linux (debian) (pull_request) Successful in 4m30s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m29s
CI Code / Linux (arch) (pull_request) Successful in 4m44s
CI Code / Check spelling (push) Successful in 18s
CI Code / Check coding style (push) Successful in 33s
CI Code / Code Coverage (push) Successful in 3m4s
CI Code / Linux (ubuntu) (push) Successful in 4m29s
CI Code / Linux (debian) (push) Successful in 4m33s
CI Code / Linux (arch) (push) Successful in 4m48s
Replace 16 interactive UI setup commands with pre-written profrc file
containing [ui] and [notifications] sections (~1800ms saved per test).

Replace sleep(1) + blocking waitpid with close(pty fd) → SIGHUP →
polling waitpid(WNOHANG) → SIGTERM/SIGKILL fallback chain (~4900ms
saved per test).

Remove post-stbbr_start() and post-stbbr_stop() sleeps — bind+listen
completes synchronously before stbbr_start() returns, and
pthread_join() in stbbr_stop() guarantees socket cleanup (~200ms saved).

Add PORTS_PER_GROUP=50 isolated port ranges per test group to enable
safe parallel execution of 4 groups without port conflicts.
2026-03-12 18:20:35 +03:00
9ec01fa8cc fix: CWE-134 format string audit and compiler hardening
All checks were successful
CI Code / Check spelling (push) Successful in 20s
CI Code / Check coding style (push) Successful in 36s
CI Code / Code Coverage (push) Successful in 5m38s
CI Code / Linux (ubuntu) (push) Successful in 7m1s
CI Code / Linux (debian) (push) Successful in 7m5s
CI Code / Linux (arch) (push) Successful in 7m19s
Security:
Fix CWE-134 in iq.c: user-controlled string passed as format argument
Add G_GNUC_PRINTF annotations to all variadic printf-like wrappers
in ui.h, log.h and http_common.h
Compiler flags (configure.ac):

Replace basic -Wformat/-Wformat-nonliteral with -Wformat=2
Add -Wextra, -Wnull-dereference, -Wpointer-arith,
-Wimplicit-function-declaration, -Wundef, -Wfloat-equal,
-Wredundant-decls, -Walloc-zero
Add -fstack-protector-strong, -fno-common, -D_FORTIFY_SOURCE=2
Add GCC-specific flags via AC_COMPILE_IFELSE: -Wlogical-op,
-Wduplicated-cond, -Wduplicated-branches, -Wstringop-overflow,
-Warray-bounds=2
Suppress noisy -Wextra sub-warnings: -Wno-unused-parameter,
-Wno-missing-field-initializers, -Wno-sign-compare,
-Wno-cast-function-type
Remove AM_CFLAGS/CFLAGS duplication
Bug fixes found by new warnings:

chatlog.c: non-MUCPM redact path passed resourcepart instead of NULL
rosterwin.c: merge duplicated if/else branches into single condition
omemo.c: redundant else-if in omemo_automatic_start; remove
unnecessary scope block and goto, use early return
console.c: pointer compared to integer 0 instead of NULL
stanza.c: increase pri_str/idle_str buffers from 10 to 12 bytes
(INT_MIN = -2147483648 needs 12 bytes including NUL)
vcard.c: NULL guard for filename before g_file_set_contents
api.c: broken log_warning() calls with extra format argument
Format mismatch fixes:

chatwin.c: Jid* → char* for %s
connection.c: %x → %lx for long flags
cmd_funcs.c: %d → %zu for size_t; cast gpointer to char* for %s
cmd_defs.c: %d → %u for g_list_length() return (guint)
iq.c: barejid → fulljid for from_jid
console.c, mucwin.c, privwin.c, account.c, omemo.c, presence.c:
gpointer → (char*) casts for %s
Const-correctness and cleanup:

database.c: const for type, query, sort variables
form.c/xmpp.h: const for form_set_value parameter
files.c: refactor to early return, eliminating NULL logfile path
muc.c/muc.h: remove meaningless top-level const on return type
common.c: const for URL string literal
Remove stale declarations: cons_show_desktop_prefs (ui.h),
connection_set_priority (connection.h),
omemo_devicelist_configure_and_request (omemo.h)
test_common.c: add currb NULL check to silence -Wnull-dereference
Tooling (check-cwe134.sh):

Reduce from 5 checks to 2 (checks 1-3 redundant with -Wformat=2)
Check 1: verify known wrappers have G_GNUC_PRINTF attribute
Check 2: auto-detect unannotated variadic printf-like functions
Match both const char* and const gchar* in variadic patterns

Author: jabber.developer2 <jabber.developer2@jabber.space>
2026-03-07 11:55:50 +01:00
1508f27e73 Merge branch 'ci/separate-build-step'
All checks were successful
CI Code / Check spelling (push) Successful in 21s
CI Code / Check coding style (push) Successful in 37s
CI Code / Code Coverage (push) Successful in 5m35s
CI Code / Linux (debian) (push) Successful in 6m56s
CI Code / Linux (ubuntu) (push) Successful in 7m2s
CI Code / Linux (arch) (push) Successful in 7m24s
2026-03-05 18:36:13 +01:00
d4254db814 CI: Separate build and test steps
All checks were successful
CI Code / Check coding style (pull_request) Successful in 32s
CI Code / Check spelling (pull_request) Successful in 24s
CI Code / Code Coverage (pull_request) Successful in 4m46s
CI Code / Linux (debian) (pull_request) Successful in 6m5s
CI Code / Linux (ubuntu) (pull_request) Successful in 6m11s
CI Code / Linux (arch) (pull_request) Successful in 6m25s
2026-03-04 23:04:51 +03:00
9e1b95a814 test(disco): remove disco_items_error_handling test
All checks were successful
CI Code / Check spelling (pull_request) Successful in 22s
CI Code / Check coding style (pull_request) Successful in 40s
CI Code / Linux (debian) (pull_request) Successful in 6m59s
CI Code / Linux (arch) (pull_request) Successful in 7m21s
CI Code / Linux (ubuntu) (pull_request) Successful in 7m13s
CI Code / Code Coverage (pull_request) Successful in 10m59s
CI Code / Check spelling (push) Successful in 20s
CI Code / Check coding style (push) Successful in 36s
CI Code / Code Coverage (push) Successful in 5m43s
CI Code / Linux (ubuntu) (push) Successful in 7m9s
CI Code / Linux (debian) (push) Successful in 10m5s
CI Code / Linux (arch) (push) Successful in 12m0s
This test requires the fix from fix/xep-0030-disco-items-error-handling
branch. Moved there along with the source code fix.
2026-03-03 16:57:35 +01:00
24e1dac354 test(disco): add comprehensive XEP-0030 functional tests
Add 7 new tests for /disco command:
- disco_items_to_jid: query items to specific JID
- disco_info_empty_result: handle empty disco#info response
- disco_info_multiple_identities: multiple identity elements
- disco_info_without_name: identity without optional name attr
- disco_items_without_name: items without optional name attr
- disco_info_service_unavailable: error handling for info
- disco_items_error_handling: error handling for items (XEP-0030 §7)

The disco_items_error_handling test documents a bug where disco#items
errors are silently ignored (unlike disco#info which handles them).
This violates XEP-0030 Section 7 which requires error feedback to user.
2026-03-03 16:57:35 +01:00
f20a4da160 Add functional tests for /disco command (XEP-0030)
- Add 8 tests for disco info and disco items commands
- Fix XEP-0030 compliance bug: show message for empty disco#items results
- Tests cover: identity display, features, server/jid queries, error handling,
  items display, empty results, and connection requirement
2026-03-03 16:57:35 +01:00
663a959f9c test: add functional tests for autoping (XEP-0199)
- autoping_set_interval: verify /autoping set command
- autoping_set_zero_disables: verify disabling autoping
- autoping_timeout_set: verify /autoping timeout command
- autoping_timeout_zero_disables: verify disabling timeout
- autoping_sends_ping_after_interval: verify automatic ping IQ
- autoping_server_not_supporting_ping: verify error handling

Fast tests (command parsing) in Group 1, slow tests (timer-based) in Group 3.
2026-03-03 16:57:35 +01:00
40 changed files with 3476 additions and 149 deletions

View File

@@ -29,10 +29,10 @@ jobs:
name: Linux
steps:
- uses: actions/checkout@v4
- name: Build
run: docker build -f Dockerfile.${{ matrix.flavor }} -t profanity .
- name: Run tests
run: |
docker build -f Dockerfile.${{ matrix.flavor }} -t profanity .
docker run profanity ./ci-build.sh
run: docker run profanity ./ci-build.sh
code-style:
runs-on: ubuntu-latest
@@ -107,7 +107,7 @@ jobs:
name: Code Coverage
steps:
- uses: actions/checkout@v4
- name: Build and run coverage
run: |
docker build -f Dockerfile.arch -t profanity-cov .
docker run profanity-cov ./ci-build.sh --coverage-only
- name: Build
run: docker build -f Dockerfile.arch -t profanity-cov .
- name: Run coverage
run: docker run profanity-cov ./ci-build.sh --coverage-only

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 = \
@@ -186,6 +191,8 @@ functionaltest_sources = \
tests/functionaltests/test_muc.c tests/functionaltests/test_muc.h \
tests/functionaltests/test_disconnect.c tests/functionaltests/test_disconnect.h \
tests/functionaltests/test_lastactivity.c tests/functionaltests/test_lastactivity.h \
tests/functionaltests/test_autoping.c tests/functionaltests/test_autoping.h \
tests/functionaltests/test_disco.c tests/functionaltests/test_disco.h \
tests/functionaltests/functionaltests.c
main_source = src/main.c
@@ -289,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

@@ -72,13 +72,13 @@ echo ""
KNOWN_RE=$(IFS="|"; echo "${REQUIRED_ATTRIBUTED[*]}")
# Find variadic declarations with a const char* parameter followed by ...)
# Find variadic declarations with a const char* / gchar* parameter followed by ...)
# that do NOT have a format attribute on the preceding line
NEW_ISSUES=$(grep -B1 -rn --include="*.h" \
'const char\s*\*.*,\s*\.\.\.)' "$DIR" 2>/dev/null \
'const g\?char\s*\*.*,\s*\.\.\.)' "$DIR" 2>/dev/null \
| awk '
/format\(printf|G_GNUC_PRINTF/ { skip=1; next }
/const char.*,.*\.\.\.\)/ {
/const g?char.*,.*\.\.\.\)/ {
if (skip) { skip=0; next }
print
}

View File

@@ -86,7 +86,6 @@ extract_test_count() {
# and checks that the test framework reports the failure correctly
verify_test_failure_detection()
{
echo
echo "==> Verifying test failure detection..."
# Create a simple failing test
@@ -205,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

@@ -981,9 +981,7 @@ _rosterwin_unsubscribed_header(ProfLayoutSplit* layout, GList* wins)
auto_gchar gchar* countpref = prefs_get_string(PREF_ROSTER_COUNT);
if (g_strcmp0(countpref, "items") == 0) {
int itemcount = g_list_length(wins);
if (itemcount == 0 && prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(header, " (%d)", itemcount);
} else if (itemcount > 0) {
if (itemcount != 0 || prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(header, " (%d)", itemcount);
}
} else if (g_strcmp0(countpref, "unread") == 0) {
@@ -994,9 +992,7 @@ _rosterwin_unsubscribed_header(ProfLayoutSplit* layout, GList* wins)
unreadcount += chatwin->unread;
curr = g_list_next(curr);
}
if (unreadcount == 0 && prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(header, " (%d)", unreadcount);
} else if (unreadcount > 0) {
if (unreadcount != 0 || prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(header, " (%d)", unreadcount);
}
}
@@ -1026,9 +1022,7 @@ _rosterwin_contacts_header(ProfLayoutSplit* layout, const char* const title, GSL
auto_gchar gchar* countpref = prefs_get_string(PREF_ROSTER_COUNT);
if (g_strcmp0(countpref, "items") == 0) {
int itemcount = g_slist_length(contacts);
if (itemcount == 0 && prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(header, " (%d)", itemcount);
} else if (itemcount > 0) {
if (itemcount != 0 || prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(header, " (%d)", itemcount);
}
} else if (g_strcmp0(countpref, "unread") == 0) {
@@ -1043,9 +1037,7 @@ _rosterwin_contacts_header(ProfLayoutSplit* layout, const char* const title, GSL
}
curr = g_slist_next(curr);
}
if (unreadcount == 0 && prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(header, " (%d)", unreadcount);
} else if (unreadcount > 0) {
if (unreadcount != 0 || prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(header, " (%d)", unreadcount);
}
}
@@ -1136,9 +1128,7 @@ _rosterwin_private_header(ProfLayoutSplit* layout, GList* privs)
auto_gchar gchar* countpref = prefs_get_string(PREF_ROSTER_COUNT);
if (g_strcmp0(countpref, "items") == 0) {
int itemcount = g_list_length(privs);
if (itemcount == 0 && prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(title_str, " (%d)", itemcount);
} else if (itemcount > 0) {
if (itemcount != 0 || prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(title_str, " (%d)", itemcount);
}
} else if (g_strcmp0(countpref, "unread") == 0) {
@@ -1149,9 +1139,7 @@ _rosterwin_private_header(ProfLayoutSplit* layout, GList* privs)
unreadcount += privwin->unread;
curr = g_list_next(curr);
}
if (unreadcount == 0 && prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(title_str, " (%d)", unreadcount);
} else if (unreadcount > 0) {
if (unreadcount != 0 || prefs_get_boolean(PREF_ROSTER_COUNT_ZERO)) {
g_string_append_printf(title_str, " (%d)", unreadcount);
}
}

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

@@ -517,32 +517,29 @@ _omemo_receive_devicelist(xmpp_stanza_t* const stanza, void* const userdata)
log_warning("[OMEMO] User %s has a non 'current' device item list: %s.", from, xmpp_stanza_get_id(first));
item = first;
} else {
goto out;
omemo_set_device_list(from, device_list);
return 1;
}
/* New scope to keep declarations after goto out above */
{
xmpp_stanza_t* list = xmpp_stanza_get_child_by_ns(item, STANZA_NS_OMEMO);
if (!list) {
return 1;
xmpp_stanza_t* list = xmpp_stanza_get_child_by_ns(item, STANZA_NS_OMEMO);
if (!list) {
return 1;
}
xmpp_stanza_t* device;
for (device = xmpp_stanza_get_children(list); device != NULL; device = xmpp_stanza_get_next(device)) {
if (g_strcmp0(xmpp_stanza_get_name(device), "device") != 0) {
continue;
}
xmpp_stanza_t* device;
for (device = xmpp_stanza_get_children(list); device != NULL; device = xmpp_stanza_get_next(device)) {
if (g_strcmp0(xmpp_stanza_get_name(device), "device") != 0) {
continue;
}
const char* id = xmpp_stanza_get_id(device);
if (id != NULL) {
device_list = g_list_append(device_list, GINT_TO_POINTER(strtoul(id, NULL, 10)));
} else {
log_error("[OMEMO] received device without ID");
}
const char* id = xmpp_stanza_get_id(device);
if (id != NULL) {
device_list = g_list_append(device_list, GINT_TO_POINTER(strtoul(id, NULL, 10)));
} else {
log_error("[OMEMO] received device without ID");
}
}
out:
omemo_set_device_list(from, device_list);
return 1;

View File

@@ -15,9 +15,9 @@
* functional tests run less frequently than unit tests.
*
* Tests are organized into groups for better maintainability and parallel execution:
* Group 1: Connect, Ping, Rooms, Software
* Group 1: Connect, Ping, Autoping (fast), Rooms, Software, Last Activity
* Group 2: Message, Receipts, Roster, Chat Session
* Group 3: Presence, Disconnect
* Group 3: Presence, Disconnect, Autoping (slow)
* Group 4: MUC, Carbons
*
* Parallel execution:
@@ -53,6 +53,8 @@
#include "test_muc.h"
#include "test_disconnect.h"
#include "test_lastactivity.h"
#include "test_autoping.h"
#include "test_disco.h"
/* Macro to wrap each test with setup/teardown functions */
#define PROF_FUNC_TEST(test) cmocka_unit_test_setup_teardown(test, init_prof_test, close_prof_test)
@@ -109,6 +111,16 @@ main(int argc, char* argv[])
/* Last Activity - XEP-0012 */
PROF_FUNC_TEST(responds_to_last_activity_request),
PROF_FUNC_TEST(last_activity_request_to_contact),
/* Autoping command tests - fast, no waiting */
PROF_FUNC_TEST(autoping_set_interval),
PROF_FUNC_TEST(autoping_set_zero_disables),
PROF_FUNC_TEST(autoping_timeout_set),
PROF_FUNC_TEST(autoping_timeout_zero_disables),
/* Autoping slow tests - require sleep for timer triggers (~2s each) */
PROF_FUNC_TEST(autoping_sends_ping_after_interval),
PROF_FUNC_TEST(autoping_server_not_supporting_ping),
};
/* ============================================================
@@ -143,7 +155,7 @@ main(int argc, char* argv[])
};
/* ============================================================
* GROUP 3: Presence, Disconnect
* GROUP 3: Presence, Disconnect, Disco
* Online/away/xa/dnd/chat status management
* ============================================================ */
const struct CMUnitTest group3_tests[] = {
@@ -165,6 +177,22 @@ main(int argc, char* argv[])
/* Disconnect - clean session termination */
PROF_FUNC_TEST(disconnect_ends_session),
/* Service Discovery - XEP-0030 */
PROF_FUNC_TEST(disco_info_shows_identity),
PROF_FUNC_TEST(disco_info_shows_features),
PROF_FUNC_TEST(disco_info_to_server),
PROF_FUNC_TEST(disco_info_to_jid),
PROF_FUNC_TEST(disco_info_not_found),
PROF_FUNC_TEST(disco_items_shows_items),
PROF_FUNC_TEST(disco_items_empty_result),
PROF_FUNC_TEST(disco_requires_connection),
PROF_FUNC_TEST(disco_items_to_jid),
PROF_FUNC_TEST(disco_info_empty_result),
PROF_FUNC_TEST(disco_info_multiple_identities),
PROF_FUNC_TEST(disco_info_without_name),
PROF_FUNC_TEST(disco_items_without_name),
PROF_FUNC_TEST(disco_info_service_unavailable),
};
/* ============================================================
@@ -212,9 +240,9 @@ main(int argc, char* argv[])
const struct CMUnitTest* tests;
size_t count;
} groups[] = {
{ "Group 1: Connect/Ping/Rooms/Software", group1_tests, ARRAY_SIZE(group1_tests) },
{ "Group 1: Connect/Ping/Rooms/Software/Autoping", group1_tests, ARRAY_SIZE(group1_tests) },
{ "Group 2: Message/Receipts/Roster/Session", group2_tests, ARRAY_SIZE(group2_tests) },
{ "Group 3: Presence/Disconnect", group3_tests, ARRAY_SIZE(group3_tests) },
{ "Group 3: Presence/Disconnect/Disco", group3_tests, ARRAY_SIZE(group3_tests) },
{ "Group 4: MUC/Carbons", group4_tests, ARRAY_SIZE(group4_tests) },
};
const int num_groups = ARRAY_SIZE(groups);

View File

@@ -12,6 +12,7 @@
#include <fcntl.h>
#include <sys/select.h>
#include <regex.h>
#include <signal.h>
#include <stabber.h>
@@ -20,11 +21,41 @@
/* Number of parallel test groups for CI builds */
#define TEST_GROUPS 4
/* Number of ports reserved per test group; allows skipping TIME_WAIT ports */
#define PORTS_PER_GROUP 50
/* Base port and fallback scan range for stabber */
#define BASE_PORT 5230
#define FALLBACK_PORT_RANGE (TEST_GROUPS * PORTS_PER_GROUP)
/* Shutdown polling: interval and maximum attempts before escalating signals */
#define MS_TO_US 1000
#define SHUTDOWN_POLL_MS 50
#define SHUTDOWN_POLL_MAX 100 /* 100 x 50ms = 5s */
#define SIGTERM_POLL_MAX 20 /* 20 x 50ms = 1s */
#define QUIT_GRACE_MS 100 /* grace for /quit to be read from pty */
#define INIT_WAIT_MS 50 /* wait for child process to initialize */
#define INPUT_DELAY_MS 10 /* let profanity process input */
#define OUTPUT_POLL_MS 50 /* polling interval for output checks */
#define READ_TIMEOUT_MS 100 /* select() timeout for pty reads */
/* Expect timeouts (seconds) */
#define EXPECT_TIMEOUT_DEFAULT 30
#define EXPECT_TIMEOUT_CONNECT 60
/* Terminal dimensions for forkpty */
#define PTY_ROWS 24
#define PTY_COLS 300
/* Preprocessor stringification (for setenv from numeric #define) */
#define STRINGIFY_(x) #x
#define STRINGIFY(x) STRINGIFY_(x)
char *config_orig;
char *data_orig;
int fd = 0;
int stub_port = 5230;
int stub_port = BASE_PORT;
pid_t child_pid = 0;
/*
@@ -44,7 +75,7 @@ static char output_buffer[OUTPUT_BUF_SIZE];
static size_t output_len = 0;
/* Timeout for expect operations in seconds */
static int expect_timeout = 30;
static int expect_timeout = EXPECT_TIMEOUT_DEFAULT;
gboolean
_create_dir(const char *name)
@@ -153,6 +184,12 @@ _cleanup_dirs(void)
}
}
static void
sleep_ms(int ms)
{
usleep(ms * MS_TO_US);
}
/*
* Read available data from fd into output_buffer with timeout.
* Returns number of bytes read, 0 on timeout, -1 on error.
@@ -166,8 +203,8 @@ _read_output(int timeout_ms)
FD_ZERO(&readfds);
FD_SET(fd, &readfds);
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
tv.tv_sec = timeout_ms / MS_TO_US;
tv.tv_usec = (timeout_ms % MS_TO_US) * MS_TO_US;
int ret = select(fd + 1, &readfds, NULL, NULL, &tv);
if (ret <= 0) {
@@ -198,8 +235,8 @@ void
prof_start(void)
{
struct winsize ws;
ws.ws_row = 24;
ws.ws_col = 300; /* Match COLUMNS=300 from start_profanity.sh */
ws.ws_row = PTY_ROWS;
ws.ws_col = PTY_COLS;
ws.ws_xpixel = 0;
ws.ws_ypixel = 0;
@@ -216,7 +253,7 @@ prof_start(void)
if (child_pid == 0) {
/* Child process */
setenv("COLUMNS", "300", 1);
setenv("COLUMNS", STRINGIFY(PTY_COLS), 1);
setenv("TERM", "xterm", 1);
execl("./profanity", "./profanity", "-l", "DEBUG", NULL);
@@ -232,7 +269,7 @@ prof_start(void)
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
/* Brief wait for process to initialize */
usleep(50000); /* 50ms */
sleep_ms(INIT_WAIT_MS);
}
int
@@ -246,38 +283,41 @@ init_prof_test(void **state)
const char *build_env = getenv("PROF_BUILD_INDEX");
int build_idx = build_env ? atoi(build_env) : 0;
/* Calculate port base: each build uses a different range of TEST_GROUPS ports.
* Build 0 (local/default): 5230-5233, Full: 5230-5233, Minimal: 5234-5237, etc.
* Build 0 and Full share the same range because build 0 is for local runs or sequential run (no parallel builds),
* while Full/Minimal/NoEncrypt/Default are used in CI where they run in parallel. */
int port_base = 5230 + ((build_idx > 0 ? build_idx - 1 : 0) * TEST_GROUPS);
/* Calculate port base: each build uses a different range of
* TEST_GROUPS * PORTS_PER_GROUP ports.
* Build 0 (local/default): 5230-5429, Full: 5230-5429, Minimal: 5430-5629, etc.
* Build 0 and Full share the same range because build 0 is for local runs
* or sequential run (no parallel builds), while Full/Minimal/NoEncrypt/Default
* are used in CI where they run in parallel. */
int port_base = BASE_PORT + ((build_idx > 0 ? build_idx - 1 : 0) * TEST_GROUPS * PORTS_PER_GROUP);
/* Static resource allocation to avoid conflicts in parallel execution.
* Group 1-4: use static port assignment.
* Group 0 (all groups): use dynamic allocation as fallback. */
/* Each group gets a dedicated range of ports for parallel execution.
* Group 1: port_base..port_base+PORTS_PER_GROUP-1
* Group 2: port_base+PORTS_PER_GROUP..port_base+2*PORTS_PER_GROUP-1, etc.
* Ports in TIME_WAIT from previous tests are skipped automatically. */
gboolean started = FALSE;
if (group >= 1 && group <= TEST_GROUPS) {
/* Static allocation: each group gets a dedicated port */
stub_port = port_base + group - 1;
printf("[PROF_TEST] Build %d, Group %d: trying port %d\n", build_idx, group, stub_port);
if (stbbr_start(STBBR_LOGDEBUG, stub_port, 0) == 0) {
started = TRUE;
printf("[PROF_TEST] Started stabber on port %d\n", stub_port);
} else {
printf("[PROF_TEST] Failed to start stabber on port %d\n", stub_port);
}
}
/* Fallback to dynamic allocation if static failed or group=0 */
if (!started) {
printf("[PROF_TEST] Using dynamic port allocation\n");
for (int p = port_base; p < port_base + 20; ++p) {
int group_port_base = port_base + (group - 1) * PORTS_PER_GROUP;
for (int p = group_port_base; p < group_port_base + PORTS_PER_GROUP && !started; p++) {
if (stbbr_start(STBBR_LOGDEBUG, p, 0) == 0) {
stub_port = p;
started = TRUE;
}
}
if (!started) {
fprintf(stderr, "[PROF_TEST] Failed to start stabber on ports %d-%d\n",
group_port_base, group_port_base + PORTS_PER_GROUP - 1);
}
}
/* Fallback to dynamic allocation if static failed or group=0 */
if (!started) {
for (int p = port_base; p < port_base + FALLBACK_PORT_RANGE; ++p) {
if (stbbr_start(STBBR_LOGDEBUG, p, 0) == 0) {
stub_port = p;
started = TRUE;
printf("[PROF_TEST] Started stabber on port %d\n", stub_port);
break;
}
}
@@ -299,9 +339,6 @@ init_prof_test(void **state)
printf("[PROF_TEST] Group %d using directories: config=%s, data=%s\n",
group, xdg_config_home, xdg_data_home);
// Give stabber server thread time to start listening
usleep(100000); // 100ms
config_orig = getenv("XDG_CONFIG_HOME");
data_orig = getenv("XDG_DATA_HOME");
@@ -315,38 +352,37 @@ init_prof_test(void **state)
_create_chatlogs_dir();
_create_logs_dir();
/* Pre-write profrc with UI/notification defaults to ensure consistent,
* deterministic output across tests (no timestamps, no roster/occupants
* panels, low input-blocking delay for fast command processing). */
char profrc_path[512];
snprintf(profrc_path, sizeof(profrc_path),
"%s/profanity/profrc", xdg_config_home);
FILE* prc = fopen(profrc_path, "w");
if (prc) {
fprintf(prc,
"[ui]\n"
"inpblock=5\n"
"inpblock.dynamic=false\n"
"wrap=false\n"
"roster=false\n"
"occupants=false\n"
"time.console=off\n"
"time.chat=off\n"
"time.muc=off\n"
"time.config=off\n"
"time.private=off\n"
"time.xmlconsole=off\n"
"[notifications]\n"
"message=false\n"
"room=false\n");
fclose(prc);
}
prof_start();
int prof_started = prof_output_regex("CProof\\. Type /help for help information\\.");
assert_true(prof_started);
// set UI options to make expect assertions faster and more reliable
prof_input("/inpblock timeout 5");
assert_true(prof_output_regex("Input blocking set to 5 milliseconds"));
prof_input("/inpblock dynamic off");
assert_true(prof_output_regex("Dynamic input blocking disabled"));
prof_input("/notify chat off");
assert_true(prof_output_regex("Chat notifications disabled"));
prof_input("/notify room off");
assert_true(prof_output_regex("Room notifications disabled"));
prof_input("/wrap off");
assert_true(prof_output_regex("Word wrap disabled"));
prof_input("/roster hide");
assert_true(prof_output_regex("Roster disabled"));
prof_input("/occupants default hide");
assert_true(prof_output_regex("Occupant list disabled"));
prof_input("/time console off");
prof_input("/time console off");
assert_true(prof_output_regex("Console time display disabled\\."));
prof_input("/time chat off");
assert_true(prof_output_regex("Chat time display disabled\\."));
prof_input("/time muc off");
assert_true(prof_output_regex("MUC time display disabled\\."));
prof_input("/time config off");
assert_true(prof_output_regex("Config time display disabled\\."));
prof_input("/time private off");
assert_true(prof_output_regex("Private chat time display disabled\\."));
prof_input("/time xml off");
assert_true(prof_output_regex("XML Console time display disabled\\."));
return 0;
}
@@ -355,14 +391,33 @@ close_prof_test(void **state)
{
if (fd > 0 && child_pid > 0) {
prof_input("/quit");
// Give profanity time to process quit command
sleep(1);
waitpid(child_pid, NULL, 0);
/* Close pty master after brief grace — child gets SIGHUP which
* accelerates shutdown instead of waiting for XMPP disconnect
* timeout (~5s). */
sleep_ms(QUIT_GRACE_MS);
close(fd);
fd = 0;
int exited = 0;
for (int i = 0; i < SHUTDOWN_POLL_MAX; i++) {
if (waitpid(child_pid, NULL, WNOHANG) != 0) {
exited = 1;
break;
}
sleep_ms(SHUTDOWN_POLL_MS);
}
if (!exited) {
kill(child_pid, SIGTERM);
for (int i = 0; i < SIGTERM_POLL_MAX; i++) {
if (waitpid(child_pid, NULL, WNOHANG) != 0) { exited = 1; break; }
sleep_ms(SHUTDOWN_POLL_MS);
}
if (!exited) {
kill(child_pid, SIGKILL);
waitpid(child_pid, NULL, 0);
}
}
child_pid = 0;
}
_cleanup_dirs();
if (config_orig) {
setenv("XDG_CONFIG_HOME", config_orig, 1);
@@ -372,13 +427,6 @@ close_prof_test(void **state)
}
stbbr_stop();
/*
* TODO: Replace with proper synchronization.
* stabber doesn't provide wait_stopped() API yet, so we use delay
* to ensure the port is released before the next test starts.
* See: https://git.jabber.space/devs/stabber/issues/3
*/
usleep(100000); // 100ms
return 0;
}
@@ -392,7 +440,7 @@ prof_input(const char *input)
g_string_free(inp_str, TRUE);
/* Small delay to let profanity process input */
usleep(10000);
sleep_ms(INPUT_DELAY_MS);
}
/*
@@ -406,7 +454,7 @@ prof_output_exact(const char *text)
while (time(NULL) - start < expect_timeout) {
/* Read any available output */
while (_read_output(100) > 0) {
while (_read_output(READ_TIMEOUT_MS) > 0) {
/* Keep reading while data available */
}
@@ -415,7 +463,7 @@ prof_output_exact(const char *text)
return 1;
}
usleep(50000); /* 50ms */
sleep_ms(OUTPUT_POLL_MS);
}
return 0;
@@ -440,7 +488,7 @@ prof_output_regex(const char *pattern)
while (time(NULL) - start < expect_timeout) {
/* Read any available output */
while (_read_output(100) > 0) {
while (_read_output(READ_TIMEOUT_MS) > 0) {
/* Keep reading while data available */
}
@@ -451,7 +499,7 @@ prof_output_regex(const char *pattern)
return 1;
}
usleep(50000); /* 50ms */
sleep_ms(OUTPUT_POLL_MS);
}
/* Timeout reached - log diagnostic info */
@@ -493,12 +541,12 @@ prof_connect_with_roster(const char *roster)
assert_true(prof_output_regex("password:"));
prof_input("password");
expect_timeout = 60;
expect_timeout = EXPECT_TIMEOUT_CONNECT;
assert_true(prof_output_regex("Connecting as stabber@localhost"));
assert_true(prof_output_regex("logged in successfully"));
assert_true(prof_output_regex(".+online.+ \\(priority 0\\)\\."));
expect_timeout = 60;
expect_timeout = EXPECT_TIMEOUT_CONNECT;
// Wait for presence stanza to be sent (content-based, not ID-based)
// Match the actual attribute order from stanza_attach_caps
assert_true(stbbr_received(
@@ -517,7 +565,7 @@ prof_timeout(int timeout)
void
prof_timeout_reset(void)
{
expect_timeout = 60;
expect_timeout = EXPECT_TIMEOUT_CONNECT;
}
void

View File

@@ -0,0 +1,114 @@
#include <glib.h>
#include "prof_cmocka.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stabber.h>
#include "proftest.h"
void
autoping_set_interval(void** state)
{
prof_connect();
prof_input("/autoping set 60");
assert_true(prof_output_exact("Autoping interval set to 60 seconds."));
}
void
autoping_set_zero_disables(void** state)
{
prof_connect();
prof_input("/autoping set 0");
assert_true(prof_output_exact("Autoping disabled."));
}
void
autoping_timeout_set(void** state)
{
prof_connect();
prof_input("/autoping timeout 30");
assert_true(prof_output_exact("Autoping timeout set to 30 seconds."));
}
void
autoping_timeout_zero_disables(void** state)
{
prof_connect();
prof_input("/autoping timeout 0");
assert_true(prof_output_exact("Autoping timeout disabled."));
}
void
autoping_sends_ping_after_interval(void** state)
{
/*
* This test verifies that autoping sends a ping IQ after the configured
* interval. We set a short interval (1 second) and verify the ping is sent.
*/
// Register disco#info response with ping support
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='result' from='localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#info'>"
"<identity category='server' type='im' name='Stabber'/>"
"<feature var='urn:xmpp:ping'/>"
"</query>"
"</iq>"
);
// Register ping response
stbbr_for_query("urn:xmpp:ping",
"<iq from='localhost' to='stabber@localhost/profanity' type='result'/>"
);
prof_connect();
// Set short autoping interval
prof_input("/autoping set 1");
assert_true(prof_output_exact("Autoping interval set to 1 seconds."));
// Wait for autoping to trigger (interval + some buffer)
sleep(2);
// Verify ping was sent (no 'to' attribute means server ping)
assert_true(stbbr_received(
"<iq id='*' type='get'>"
"<ping xmlns='urn:xmpp:ping'/>"
"</iq>"
));
}
void
autoping_server_not_supporting_ping(void** state)
{
/*
* When server doesn't support ping, autoping should show error.
*/
// Register disco#info response WITHOUT ping support
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='result' from='localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#info'>"
"<identity category='server' type='im' name='Stabber'/>"
"</query>"
"</iq>"
);
prof_connect();
// Set short autoping interval
prof_input("/autoping set 1");
assert_true(prof_output_exact("Autoping interval set to 1 seconds."));
// Wait for autoping to trigger
sleep(2);
// Should show error about ping not being supported
assert_true(prof_output_regex("Server ping not supported"));
}

View File

@@ -0,0 +1,6 @@
void autoping_set_interval(void** state);
void autoping_set_zero_disables(void** state);
void autoping_timeout_set(void** state);
void autoping_timeout_zero_disables(void** state);
void autoping_sends_ping_after_interval(void** state);
void autoping_server_not_supporting_ping(void** state);

View File

@@ -0,0 +1,420 @@
/*
* test_disco.c
*
* Functional tests for /disco command (XEP-0030 Service Discovery).
* Tests cover:
* - /disco info [jid] - query entity capabilities and features
* - /disco items [jid] - query entity items/services
*
* XEP-0030: https://xmpp.org/extensions/xep-0030.html
*/
#include <glib.h>
#include "prof_cmocka.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stabber.h>
#include "proftest.h"
void
disco_info_shows_identity(void **state)
{
/*
* Test that /disco info displays identity information correctly.
* Identity includes: name, type, category
*/
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='result' from='localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#info'>"
"<identity category='server' type='im' name='Prosody'/>"
"</query>"
"</iq>"
);
prof_connect();
prof_input("/disco info");
prof_timeout(10);
assert_true(prof_output_exact("Service discovery info for localhost"));
assert_true(prof_output_exact("Identities"));
assert_true(prof_output_regex("Prosody.*im.*server"));
prof_timeout_reset();
}
void
disco_info_shows_features(void **state)
{
/*
* Test that /disco info displays feature list.
*/
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='result' from='localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#info'>"
"<identity category='server' type='im' name='TestServer'/>"
"<feature var='urn:xmpp:ping'/>"
"<feature var='http://jabber.org/protocol/disco#info'/>"
"<feature var='http://jabber.org/protocol/disco#items'/>"
"</query>"
"</iq>"
);
prof_connect();
prof_input("/disco info");
prof_timeout(10);
assert_true(prof_output_exact("Features:"));
assert_true(prof_output_exact("urn:xmpp:ping"));
assert_true(prof_output_exact("http://jabber.org/protocol/disco#info"));
prof_timeout_reset();
}
void
disco_info_to_server(void **state)
{
/*
* Test that /disco info without arguments queries the server (domainpart).
*/
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='result' from='localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#info'>"
"<identity category='server' type='im' name='LocalServer'/>"
"</query>"
"</iq>"
);
prof_connect();
prof_input("/disco info");
/* Verify request was sent to server (localhost) */
prof_timeout(10);
assert_true(stbbr_received(
"<iq id='*' to='localhost' type='get'>"
"<query xmlns='http://jabber.org/protocol/disco#info'/>"
"</iq>"
));
prof_timeout_reset();
}
void
disco_info_to_jid(void **state)
{
/*
* Test that /disco info <jid> queries the specified JID.
*/
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='result' from='conference.localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#info'>"
"<identity category='conference' type='text' name='MUC Service'/>"
"<feature var='http://jabber.org/protocol/muc'/>"
"</query>"
"</iq>"
);
prof_connect();
prof_input("/disco info conference.localhost");
prof_timeout(10);
/* Verify request was sent to specified JID */
assert_true(stbbr_received(
"<iq id='*' to='conference.localhost' type='get'>"
"<query xmlns='http://jabber.org/protocol/disco#info'/>"
"</iq>"
));
assert_true(prof_output_exact("Service discovery info for conference.localhost"));
prof_timeout_reset();
}
void
disco_info_not_found(void **state)
{
/*
* Test error handling when disco info returns item-not-found.
*/
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='error' from='unknown.localhost'>"
"<error type='cancel'>"
"<item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>"
"</error>"
"</iq>"
);
prof_connect();
prof_input("/disco info unknown.localhost");
prof_timeout(10);
assert_true(prof_output_regex("Service discovery failed.*item-not-found"));
prof_timeout_reset();
}
void
disco_items_shows_items(void **state)
{
/*
* Test that /disco items displays items list with JID and name.
*/
stbbr_for_query("http://jabber.org/protocol/disco#items",
"<iq to='stabber@localhost/profanity' type='result' from='localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#items'>"
"<item jid='conference.localhost' name='Chat Rooms'/>"
"<item jid='pubsub.localhost' name='Publish-Subscribe'/>"
"<item jid='proxy.localhost' name='SOCKS5 Bytestreams'/>"
"</query>"
"</iq>"
);
prof_connect();
prof_input("/disco items");
prof_timeout(10);
assert_true(prof_output_exact("Service discovery items for localhost:"));
assert_true(prof_output_regex("conference.localhost.*Chat Rooms"));
assert_true(prof_output_regex("pubsub.localhost.*Publish-Subscribe"));
assert_true(prof_output_regex("proxy.localhost.*SOCKS5 Bytestreams"));
/* Verify IQ was sent with correct id */
assert_true(stbbr_received(
"<iq id='discoitemsreq' to='localhost' type='get'>"
"<query xmlns='http://jabber.org/protocol/disco#items'/>"
"</iq>"
));
prof_timeout_reset();
}
void
disco_items_empty_result(void **state)
{
/*
* Test that /disco items handles empty result gracefully.
* Per XEP-0030: "if an entity has no associated items, it MUST return
* an empty <query/> element (rather than an error)"
*/
stbbr_for_query("http://jabber.org/protocol/disco#items",
"<iq to='stabber@localhost/profanity' type='result' from='localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#items'/>"
"</iq>"
);
prof_connect();
prof_input("/disco items");
prof_timeout(10);
assert_true(prof_output_exact("No service discovery items for localhost"));
prof_timeout_reset();
}
void
disco_requires_connection(void **state)
{
/*
* Test that /disco info and /disco items require an active connection.
* First test without any connection, then after connect/disconnect.
*/
/* Without connection */
prof_input("/disconnect");
assert_true(prof_output_exact("You are not currently connected."));
prof_input("/disco info");
assert_true(prof_output_exact("You are not currently connected."));
prof_input("/disco items");
assert_true(prof_output_exact("You are not currently connected."));
/* After connect and disconnect */
prof_connect();
prof_input("/disconnect");
assert_true(prof_output_exact("stabber@localhost logged out successfully."));
prof_input("/disco info");
assert_true(prof_output_exact("You are not currently connected."));
prof_input("/disco items");
assert_true(prof_output_exact("You are not currently connected."));
}
void
disco_items_to_jid(void **state)
{
/*
* Test that /disco items <jid> queries the specified JID.
*/
stbbr_for_query("http://jabber.org/protocol/disco#items",
"<iq to='stabber@localhost/profanity' type='result' from='conference.localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#items'>"
"<item jid='room1@conference.localhost' name='General Chat'/>"
"<item jid='room2@conference.localhost' name='Support'/>"
"</query>"
"</iq>"
);
prof_connect();
prof_input("/disco items conference.localhost");
prof_timeout(10);
/* Verify request was sent to specified JID */
assert_true(stbbr_received(
"<iq id='discoitemsreq' to='conference.localhost' type='get'>"
"<query xmlns='http://jabber.org/protocol/disco#items'/>"
"</iq>"
));
assert_true(prof_output_exact("Service discovery items for conference.localhost:"));
assert_true(prof_output_regex("room1@conference.localhost.*General Chat"));
prof_timeout_reset();
}
void
disco_info_empty_result(void **state)
{
/*
* Test that /disco info handles empty result (no identities/features).
* This can happen with minimal server configurations.
*/
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='result' from='minimal.localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#info'/>"
"</iq>"
);
prof_connect();
prof_input("/disco info minimal.localhost");
prof_timeout(10);
/* Verify request was sent */
assert_true(stbbr_received(
"<iq id='*' to='minimal.localhost' type='get'>"
"<query xmlns='http://jabber.org/protocol/disco#info'/>"
"</iq>"
));
/* Empty result should not crash and should not show "Service discovery info" */
prof_timeout_reset();
}
void
disco_info_multiple_identities(void **state)
{
/*
* Test that /disco info displays multiple identities correctly.
* Entities can have multiple identities (e.g., server + gateway).
*/
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='result' from='gateway.localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#info'>"
"<identity category='gateway' type='irc' name='IRC Gateway'/>"
"<identity category='directory' type='chatroom' name='Room Directory'/>"
"<identity category='automation' type='command-node' name='Ad-Hoc Commands'/>"
"</query>"
"</iq>"
);
prof_connect();
prof_input("/disco info gateway.localhost");
prof_timeout(10);
assert_true(prof_output_exact("Service discovery info for gateway.localhost"));
assert_true(prof_output_exact("Identities"));
assert_true(prof_output_regex("IRC Gateway.*irc.*gateway"));
assert_true(prof_output_regex("Room Directory.*chatroom.*directory"));
assert_true(prof_output_regex("Ad-Hoc Commands.*command-node.*automation"));
prof_timeout_reset();
}
void
disco_info_without_name(void **state)
{
/*
* Test that /disco info handles identity without name attribute.
* Per XEP-0030: name is OPTIONAL, only category and type are REQUIRED.
*/
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='result' from='localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#info'>"
"<identity category='server' type='im'/>"
"</query>"
"</iq>"
);
prof_connect();
prof_input("/disco info");
prof_timeout(10);
assert_true(prof_output_exact("Service discovery info for localhost"));
assert_true(prof_output_exact("Identities"));
/* Should show type and category even without name */
assert_true(prof_output_regex("im.*server"));
prof_timeout_reset();
}
void
disco_items_without_name(void **state)
{
/*
* Test that /disco items handles items without name attribute.
* Per XEP-0030: name is OPTIONAL for items, only jid is REQUIRED.
*/
stbbr_for_query("http://jabber.org/protocol/disco#items",
"<iq to='stabber@localhost/profanity' type='result' from='localhost'>"
"<query xmlns='http://jabber.org/protocol/disco#items'>"
"<item jid='conference.localhost'/>"
"<item jid='pubsub.localhost' name='PubSub Service'/>"
"<item jid='upload.localhost'/>"
"</query>"
"</iq>"
);
prof_connect();
prof_input("/disco items");
prof_timeout(10);
assert_true(prof_output_exact("Service discovery items for localhost:"));
/* Items without name should still display their JID */
assert_true(prof_output_exact("conference.localhost"));
assert_true(prof_output_regex("pubsub.localhost.*PubSub Service"));
assert_true(prof_output_exact("upload.localhost"));
prof_timeout_reset();
}
void
disco_info_service_unavailable(void **state)
{
/*
* Test error handling when disco info returns service-unavailable.
*/
stbbr_for_query("http://jabber.org/protocol/disco#info",
"<iq to='stabber@localhost/profanity' type='error' from='offline.localhost'>"
"<error type='cancel'>"
"<service-unavailable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>"
"</error>"
"</iq>"
);
prof_connect();
prof_input("/disco info offline.localhost");
prof_timeout(10);
assert_true(prof_output_regex("Service discovery failed.*service-unavailable"));
prof_timeout_reset();
}

View File

@@ -0,0 +1,19 @@
/* test_disco.h
*
* Functional tests for /disco command (XEP-0030 Service Discovery)
*/
void disco_info_shows_identity(void **state);
void disco_info_shows_features(void **state);
void disco_info_to_server(void **state);
void disco_info_to_jid(void **state);
void disco_info_not_found(void **state);
void disco_items_shows_items(void **state);
void disco_items_empty_result(void **state);
void disco_requires_connection(void **state);
void disco_items_to_jid(void **state);
void disco_info_empty_result(void **state);
void disco_info_multiple_identities(void **state);
void disco_info_without_name(void **state);
void disco_items_without_name(void **state);
void disco_info_service_unavailable(void **state);

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);
}